cpointersstructbsearch

C bsearch always returns pointer=NULL


Can someone tell me why in this program bsearch fuction always 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;
}

Please focus on the part with bsearch, because other thing working well.

I will be very grateful :)


Solution

  • The solution of this problem is that komparator requires type (struct data *), so

    int wanted=18;
    

    is the mistake and after changing it to

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

    everything works :)

    @BLUEPIXY helped :)