2017-06-29 67 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帮助:)