stdlib qsort & bsearch question, comparing custom defined structure arrays
I'm wondering if I can use the stdlib quicksort & binary search functions to search & sort a custom defined structure array containing a character string key. The functions would compare the key of 2 elements & use the result to search/sort structure array. Can it be done? if so, how do I modify the compare function below to make it work? Or will I have to write custom binary search & sorting functions for this situation?
//code below
typedef struct index{ // 1 entry in index contains these 3 fields
char key[7];
int rrn;
int block;
}Index;
int compare(const void* p1, const void* p2);
int main(){
Index the_index[3];
the_index[0].key[0] = 0;
the_index[1].key[0] = 0;
the_index[2].key[0] = 0;
strcat(the_index[0].key,"N87BC ");
strcat(the_index[1].key,"TC-THG");
strcat(the_index[2].key,"N1079U");
puts("Before sort:\n");
int i;
for(i = 0; i < 3; i++)
printf("%s\t",the_index[i].key);
puts(" ");
qsort((void *)the_index, 3, (2*sizeof(int)+7*sizeof(char)), compare);
puts("After sort:\n");
int i;
for(i = 0; i < 3; i++)
printf("%s\t",the_index[i].key);
puts(" ");
return 0;
}
int compare(const void* p1, const void* p2){
return strcmp(*(Index *).(char *)p1.key, *(Index *).(char *)p2.key);
}