C bsearch always returns pointer=NULL
C bsearch always returns pointer=NULL
有人能告诉我为什么在这个程序中 bsearch 函数总是 returns 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需要类型(struct data *),所以
int wanted=18;
是错误,改成
后
struct data wanted = {"", 18, ""};
一切正常:)
@BLUEPIXY 帮忙:)
有人能告诉我为什么在这个程序中 bsearch 函数总是 returns 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需要类型(struct data *),所以
int wanted=18;
是错误,改成
后struct data wanted = {"", 18, ""};
一切正常:)
@BLUEPIXY 帮忙:)