浏览 3380 次
锁定老帖子 主题:C语言的线性搜索
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
|
|
---|---|
作者 | 正文 |
发表时间:2012-07-14
最后修改:2012-07-16
#include <stdio.h> #include <string.h> #define PF printf int main() { int intcmp(void *ip1, void * ip2); void * lsearch(void *key, void *base, int n, int elemSize, int(* cmpfun)(void *, void *)); int arr[] = {4, 6, 2, 3, 11, 22, 15}; int n = sizeof(arr) / sizeof(int); int key = 11; int *found = lsearch(&key, &arr, n, sizeof(int), intcmp); PF("found=%p", found); return 1; } int intcmp(void *ip1, void * ip2) { int *p1 = ip1; int *p2 = ip2; return *p1 - *p2 == 0; } void * lsearch(void *key, void *base, int n, int elemSize, int(* cmpfun)(void *, void *)) { int i; for(i = 0; i < n; i ++) { void *elemArr = (char *)base + i * elemSize; if(cmpfun(key, elemArr) == 0) return elemArr; } return NULL; } 正确应为 #include <stdio.h> #include <string.h> //#define PF printf int main() { int intcmp(void *ip1, void * ip2); void * lsearch(void *key, void *base, int n, int elemSize, int(* cmpfun)(void *, void *)); int arr[] = {4, 6, 2, 3, 11, 22, 15}; int n = sizeof(arr) / sizeof(int); int key = 11; int *found = lsearch(&key, &arr, n, sizeof(int), intcmp); printf("found=%p (%d)", found, *(int *) found); return 0; } int intcmp(void *ip1, void * ip2) { int *p1 = ip1, *p2 = ip2; return *p1 - *p2; } void * lsearch(void *key, void *base, int n, int elemSize, int(* cmpfun)(void *, void *)) { int i; for(i = 0; i < n; i ++) { void *elemArr = (char *)base + i * elemSize; if(cmpfun(key, elemArr) == 0) return elemArr; } return NULL; } 声明:ITeye文章版权属于作者,受法律保护。没有作者书面许可不得转载。
推荐链接
|
|
返回顶楼 | |