我的lsearch
函数应该在我的数组中找到值 11。它没有,我不知道错误在哪里。为什么这段代码找不到值 11?
#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;
}