C 线性搜索误差

标签 c search

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

最佳答案

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

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

和:

return *p1 - *p2 == 0;

当两个元素相等时,在心里想一想。当数字确实等于另一个时,== 表达式将返回 1。 1 != 0 因此不认为已找到。

要么通过那里的否定,要么直接return *p1 - *p2;

关于C 线性搜索误差,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11481430/

相关文章:

c - 防止 SIGALRM 中断 waitpid()

php - 搜索引擎只能单返回?

java - 如何从 contactList 中更快地搜索给定字符串

c++ primer Binary Search 通过迭代器

c - 通过线程之间的环形(Circular)缓冲区发送消息(C语言)

在 C 中创建一个带有基本路径 + 扩展名和当前日期的文件名 [char *array]

c - 从文件中读取位时 `16 longs` 和 `110 words` 的含义是什么

c - 关于C循环的问题

arrays - 查找数组中出现奇数次的所有元素

mysql - 我正在尝试使用通配符在 MySQL 中进行搜索和替换