2017-06-29 97 views
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的部分,因爲其他事情運作良好。

我會很感激:)

+0

爲什麼定義一個二維數組&指針時,你可以只是做'結構數據人[10];'? –

+0

'komparator'不能作爲'int *'應用於'&wanted'。 – BLUEPIXY

+0

我在大學裏被問到了這個問題:S multidimentional數組在qsort中工作,它有類似的論點,所以我不認爲這是一個問題 –

回答

1

這個問題的解決方案是komparator需要的類型(結構數據*),所以

int wanted=18; 

是錯誤,將其更改爲

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

一切正常:)

@BLUEPIXY幫助:)