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"?
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
.
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 :-)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With