• 编程范式学习代码--cmpfun


     1 #include <stdio.h>
     2 #include <stdlib.h>
     3 #include <string.h>
     4 
     5 void *lsearch(void *key, void *base, int n, int elemsize, int(*Cmpfun)(void *,void *))
     6 {
     7     int i=0;
     8     for(i=0;i<n;i++)
     9     {
    10         void *elemAddr = (char*)base + i*elemsize;
    11         if(Cmpfun(key,elemAddr) == 0)
    12             return elemAddr;
    13     }
    14     return NULL;
    15 }
    16 
    17 
    18 int intCmp(void *elem1,void *elem2)
    19 {
    20     int *ip1 = elem1;
    21     int *ip2 = elem2;
    22     return (*ip1 - *ip2);
    23 }
    24 
    25 int strCmp(void *vp1,void *vp2)
    26 {
    27     char *s1 = *(char**)vp1;
    28     char *s2 = *(char**)vp2;
    29     return strcmp(s1,s2);
    30 }
    31 
    32 int main()
    33 {
    34     //测试整形数组中查找相应整数
    35 #if 0
    36     int arg[]={4,2,3,7,11,6};
    37     int size = 6;
    38     int number = 7;
    39     int *found = lsearch(&number,arg,6,sizeof(int),intCmp);
    40     if(NULL == found)
    41     {
    42         printf("no match
    ");
    43         getchar();
    44         exit(EXIT_SUCCESS);
    45     }
    46     else
    47     {
    48         printf("Found address 
    %p : %d
    ",found,number);
    49         getchar();
    50         exit(EXIT_SUCCESS);
    51     }
    52 #endif
    53     //测试字符串数组中查找相应字符串
    54 #if 1
    55     char *notes[] = {"Ab","F#","B","Gb","D"};
    56     char *serchr = "Gb";
    57     char **found=lsearch(&serchr,notes,5,sizeof(char*),strCmp);
    58     if(NULL == found)
    59     {
    60         printf("no match
    ");
    61         getchar();
    62         exit(EXIT_SUCCESS);
    63     }
    64     else
    65     {
    66         printf("Found address 
    %p : %s
    ",*found,serchr);
    67         getchar();
    68         exit(EXIT_SUCCESS);
    69     }
    70 
    71 #endif
    72 }
  • 相关阅读:
    项目中使用Redis的游标scan的一些小问题
    mac上使用Sequel Pro工具SSH连接数据库
    virtualbox通过Nat模式上网,宿主机与宿主机互通
    Mac系统docker初探
    QQ互联,填写回调时注意事项
    Centos中编辑php扩展库
    samba服务介绍
    bash常用功能
    vsftp服务介绍与相关实验
    shell概述与echo命令
  • 原文地址:https://www.cnblogs.com/wystan/p/4902520.html
Copyright © 2020-2023  润新知