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\n");
43 getchar();
44 exit(EXIT_SUCCESS);
45 }
46 else
47 {
48 printf("Found address \n%p : %d\n",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\n");
61 getchar();
62 exit(EXIT_SUCCESS);
63 }
64 else
65 {
66 printf("Found address \n%p : %s\n",*found,serchr);
67 getchar();
68 exit(EXIT_SUCCESS);
69 }
70
71 #endif
72 }