C bsearch 总是返回 pointer=NULL

标签 c pointers struct bsearch

有人能告诉我为什么在这个程序中 bsearch 函数总是返回 pointer=NULL 吗??

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

struct data
{
    char name[10];
    int age;
    char eye[15];
};



int komparator (const void* a, const void *b)
{
    struct data *aa = (struct data *)a;
    struct data *bb = (struct data *)b;
    return (aa->age-bb->age);
}

int main ()
{
    char *NAME[10]={"Ola","Tola","Jola","Zosia","Jan","Adam","Ala","Basia","Tom","Jacek"};
    char *COLOR[10]={"zielone", "brazowe", "niebieskie", "niebieskie", "zielone", "brazowe", "brazowe", "niebieskie", "czarne", "niebieskie"};

    struct data (*pointer)[5];
    struct data people[2][5];
    pointer=people;

    int i;
    for(i=0;i<2*5;i++)
    {
        strcpy((*pointer)[i].name,NAME[i]);
        strcpy((*pointer)[i].eye,COLOR[i]);
        (*pointer)[i].age=rand()%(40-18)+18;
    }

    qsort(people,2*5,sizeof(struct data),komparator);

 // here is the problem:        
    int wanted = 18;
    struct data *found=(struct data*) bsearch(&wanted,people,2*5,sizeof(struct data),komparator);

    if(found!=NULL)
    {
        printf("Found name is: %s,  eye's: %s, age: %d\n",found->name,found->eye,found->age);
    }
    else
    {
        printf("Didnt find \n");
    }
    return 0;
}

请专注于 bsearch 部分,因为其他方面工作正常。

我将不胜感激:)

最佳答案

这个问题的解决方法是komparator需要type(struct data *),所以

int wanted=18;

是错误的,改成

struct data wanted = {"", 18, ""};

一切正常:)

@BLUEPIXY 帮助了 :)

关于C bsearch 总是返回 pointer=NULL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44834031/

相关文章:

c - 从进程 ID 获取窗口标题

python - 组合图 : is there a TensorFlow import_graph_def equivalent for C++?

c++ - 紧凑的偏移指针,现有的实现?

matlab - 为什么使用空单元格构造 MATLAB 结构体对象会创建一个空结构体?

c - 错误: argument of type "HNode *" is incompatible with parameter type "HNode *"

c - 如何在 JavaScript 中保存指针并进一步检索

c# - 编码包含字符串的结构

c - 如何清除c中的字符指针数组?

c - 指针的一些代码

c++ - 从结构 vector 中查找 vector 的子序列