Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C language,Questions about character array pointers and secondary pointers and the cmp function in the qsort function

//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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading