1
有人能告訴我爲什麼在這個程序中bsearch函數總是返回指針= NULL?C 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的部分,因爲其他事情運作良好。
我會很感激:)
爲什麼定義一個二維數組&指針時,你可以只是做'結構數據人[10];'? –
'komparator'不能作爲'int *'應用於'&wanted'。 – BLUEPIXY
我在大學裏被問到了這個問題:S multidimentional數組在qsort中工作,它有類似的論點,所以我不認爲這是一個問題 –