0

我的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;
}
4

2 回答 2

4

您的代码中有一些奇怪之处(PF 以及函数在 main 中声明但全局定义的方式),但是,问题是您的逻辑如果在两个地方倒置。

if(cmpfun(key, elemArr) == 0)
        return elemArr;

和:

return *p1 - *p2 == 0;

当两个元素相等时,在心理上贯穿这一点。当数字实际上等于另一个时, == 表达式将返回 1。1 != 0 因此它不被认为是找到的。

通过那里的否定或return *p1 - *p2;直接否定。

于 2012-07-14T06:00:16.053 回答
1

我已经注释了下面的代码:

#include <stdio.h> 
#include <string.h> 

// This is bad practice. It makes your code less readable.
// I won't use it below.
#define PF printf 

// Declare this first so a prototype is not needed.
// You violated a C pattern by using `cmp` in the name.
// Comparison functions in C return <0, 0, >0, not a binary value.
// To wit, later you used the comparison correctly.  I've fixed the
// inconsistency.
int intcmp(void *vp1, void *vp2) 
{   // Most C styles have the brace on its own line, unlike Java. Roll with it.
    int *p1 = vp1, *p2 = vp2;
    return *p1 - *p2; 
}

// Search n elements of size elemSize in the array at 
// base in sequence using cmpfun on key, 
// to test for equality (cmpfun == 0).  Return a pointer 
// to the found element or NULL if none.
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; 
}

int main() 
{   
    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; // By convention zero corresponds to no error.
} 
于 2012-07-14T06:23:49.567 回答