有人能告诉我为什么在这个程序中bsearch功能总是返回指针= 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的部分,因为其他方面运作良好。
我将非常感激:)
答案 0 :(得分:1)
这个问题的解决方案是komparator需要类型(struct data *),所以
int wanted=18;
是错误,在将其更改为
之后struct data wanted = {"", 18, ""};
一切正常:)
@BLUEPIXY帮助:)