I'm making a program that's supposed to have a binary search of an array that has already been sorted by qsort( ). The qsort( ) function worked perfectly and outputted the correct sorted array, but the bsearch( ) using the same "compare" function does not seem to work correctly. I've been reading that these two functions use the same compare function together when dealing with the same types of elements. Can anyone tell me what I'm doing wrong with my bsearch function?
Code:
struct ot_entry {
char ot_mnemonic[OP_LENGTH + 1];
int ot_format;
};
struct ot_entry *optbl[OT_SIZE];
int compare_elements(const void **ptr1, const void **ptr2){
return strcmp((*(struct ot_entry**)ptr1)->ot_mnemonic, (*(struct ot_entry**)ptr2)->ot_mnemonic);
}
// sort elements by the ot_mnemonic string in ot_entry
void sortOpTbl(){
qsort(optbl, ot_count, sizeof(optbl[0]), compare_elements);
}
// find element by the ot_mnemonic string in ot_entry
void find_operation (const char *name)
{
struct ot_entry target, *result;
strcpy(target->ot_mnemonic, name);
result = bsearch (&target, optbl, ot_count, sizeof (struct ot_entry), compare_elements);
if (result){
printf("Operation %s was found", name);
}
else{
printf ("Couldn't find %s.\n", name);
}
}
int main( ){
...
char oper[OP_LENGTH + 1];
find_operation(oper);
...
return 0;
}