//Sort character array lexicographically (main code):
char* words[MAX_SIZE];
qsort(words, len, sizeof(char*), cmp);
int cmp(const void* w1, const void* w2) {
char** str1 = w1;
char** str2 = w2;
return strcmp(*str1, *str2);
//return strcmp(w1, w2);
}
Why does the cmp function have to define a secondary pointer to output normally? Why can’t it directly return strcmp(w1, w2);?
Please! Help!
My understanding is that w1 and w2 are pointers (words) pointing to the string head pointer (words[i]), \ is the pointer of the pointer, and needs to be dereferenced to compare.
Is it right?
>Solution :
The comparison function given to qsort is passed the address of two members to compare. Since the array contains elements of type char *, the address of these members has type char **.
The strcmp function expects a pair of char *, so each const void * argument must first be converted to the expected type of const char ** and dereferenced to obtain the proper type for strcmp.