Hello to all, I'm new to the forum and I have a question,
what I'm trying to do with this code is an address book and I have an array of pointers which are returned by malloc whenever I need to add an extra entry in the address book. What I need to do is search for a specific entry using bsearch. I've got an inqSort() function that sorts the table and runs normally, but my program crashes when I try to use bsearch. I can't understand what I'm doing wrong, so I was wondering if somebody could explain it to me
Code:
typedef struct {
char name[20];
char phone[14];
} abEntry;
abEntry * ab[100];
int abFreeEntry=0;
int abComp(const void *a, const void *b){
const abEntry * ab1 = *(abEntry **) a;
const abEntry * ab2 = *(abEntry **) b;
return strcasecmp(ab1->name,ab2->name);
}
void inqSort(){
qsort(ab,abFreeEntry,sizeof(abEntry *),abComp);
}
abEntry* findAbEntry(abEntry abe){
return bsearch(&abe,*ab,abFreeEntry,sizeof(abEntry *),abComp);
}
void findEntryUI(){
abEntry query, *res;
printf("Input name to be searched: ");
scanf("%s",&query.name);
res=findAbEntry(query);
if (res!=NULL){
printf("The phone number is: %s\n",res->phone);
} else {
printf("\n***Entry not found***\n");
}
}
Every time an entry is inserted, I inqsort() the array so it's always sorted, and it works as expected. But when I try to call findEntryUI(); from the main() function, the program crashes after entering the name I want to search. Any help is welcome! Thank you in advance!