cbsearch

Find person with surname that starts with character c using bsearch


I have problem finding what is wrong with my code down below. It compiles, but doesn't work properly. What it has to do is to find person with surname that starts with character c using bsearch.

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>

    typedef struct {
         char name[26];
         char surname[26];    
    } Person;

    int compare(const void *a, const void *b) {
        char x = (*((Person*)a)).surname[0];
        char y = (*((Person*)a)).surname[0];
        if(x < y) return -1;
        else if(x > y) return 1;
        else return 0;
        }

int main() {

Person array_person[]={{"Mike", "Anthony"},
                   {"Dave", "Eric"},
                   {"Danny", "Markle"},
                   {"Anne", "Redmayne"},
                   {"Lulu", "Rsu"}};

char c;
scanf("%c",&c);

Person *p;
p = (Person*)bsearch(&c,array_person,sizeof(array_person)/sizeof(Person),sizeof(Person),compare);    

printf("%s %s",p->name, p->surname);
   
return 0;                       
}

Solution

  • The first argument to the call (the parameter 'a' ) needs to be the character c and not an instance of Person. Please see down here, I hope this will help.

    int compare(const void *a, const void *b) {
     char x = (*(char*)a);
     char y = ((Person*)b)->surname[0];
     if(x < y) return -1;
     else if(x > y) return 1;
     else return 0;
    }
    
    int main() {
    
       Person array_person[]={{"Mike", "Anthony"},
                   {"Dave", "Eric"},
                   {"Danny", "Markle"},
                   {"Anne", "Redmayne"},
                   {"Lulu", "Rsu"}};
    
       char c;
       scanf("%c",&c);
    
    Person *p;
    p = (Person*)bsearch(&c,array_person,sizeof(array_person)/sizeof(Person),sizeof(Person),compare);    
    if( p==NULL )
        printf("Not found\n");
    else
        printf("%s %s\n",p->name, p->surname);
    
    return 0;                       
    

    }

    You need to note that, as you wrote the function, it will always find a person with surname starting with the given character rather than all persons. I am not sure whether this is what you are supposed to implement.