Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is the manpage of qsort(3) right?

Tags:

c

qsort

The manpage of the qsort(3) library routine gives an example of sorting the words given as arguments on the command-line. The comparison function reads 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's being sorted here are the elements of argv. Now argv is a pointer to pointers of chars, which can be viewed also as a table of pointers to chars.

Hence its elements are pointers to chars, so shouldn't the actual arguments of cmpstringp be pointers to chars, and not "pointers to pointers to char"?

like image 904
lindelof Avatar asked Jan 22 '23 03:01

lindelof


2 Answers

The callback function passed as argument to qsort() is called with, as arguments, pointers to the two values to compare. If you sort an array of char * (e.g. argv[]) then the values are char * (pointers to char) and the comparison function will receive pointers to such values, i.e. pointers to pointers to char.

like image 163
Thomas Pornin Avatar answered Jan 29 '23 14:01

Thomas Pornin


strcmp(* (char * const *) p1, * (char * const *) p2)
       ^^^^^^^^^^^^^^^^^^^^^

So p1 is of type * (char * const *) or, by removing *'s (char * const); and char *const is assignment compatible with char *, so no problem :-)

like image 42
pmg Avatar answered Jan 29 '23 15:01

pmg