Is the qsort (3) control page correct?

The qsort(3) library routine's man page shows an example of sorting words specified as arguments on the command line. The comparison function is read as follows:

 static int cmpstringp(const void *p1, const void *p2) { /* The actual arguments to this function are "pointers to pointers to char", but strcmp(3) arguments are "pointers to char", hence the following cast plus dereference */ return strcmp(* (char * const *) p1, * (char * const *) p2); } 

But what is sorted here is the argv elements. argv is now a pointer to character pointers, which can also be viewed as a table of character pointers.

Therefore, its elements are pointers to characters, so shouldn't the actual arguments to cmpstringp point to characters, and not "pointers to pointers to char"?

+4
source share
3 answers

The callback function passed as the qsort() argument is called with arguments pointing to two values ​​to compare. If you sort the char * array (for example, argv[] ), then the char * values ​​(point to char ), and the comparison function will receive pointers to such values, i.e. Pointers to pointers to char .

+7
source
  strcmp (* (char * const *) p1, * (char * const *) p2)
        ^^^^^^^^^^^^^^^^^^^^^^

So p1 is of type * (char * const *) or by removing * (char * const) ; and char *const is a match compatible with char * , so there is no problem :-)

+2
source

No, because presumably you are calling qsort as follows:

 qsort(&argv[0], argc, sizeof(char*), cmpstringp); 

i.e. you pass it a pointer to an element, and the element is const char * .

0
source

All Articles