#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
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);
}
int main(int argc, char *argv[])
{
int j;
assert(argc > 1);
qsort(&argv[1], argc - 1, sizeof(argv[1]), cmpstringp);
for (j = 1; j < argc; j++)
puts(argv[j]);
exit(EXIT_SUCCESS);
}
I'm confused with this part:
return strcmp(* (char * const *) p1, * (char * const *) p2);
Why did they do this? Why did they NOT do this: (const char**) or (const char * const*)? Don't we get a pointer to a const char if we dereference once for (const char**)? Dereferencing the second one, don't we get a const pointer that points at a const char. Both of these seem to what strcmp() asks for: two pointers who point at const chars. What the man page seems to give us const pointers pointing at non-const things, which doesn't seem to be what strcmp()'s declaration is asking for. Even if legal, it doesn't seem like a good idea to give a function something that doesn't fit its parameters. Am I missing something?
Lastly, why does the following not generate at least an error warning:
auto const char * const ptr3 = *(const char **) ptr1; //where ptr1 is
of the form int foo(const void * ptr).
Dereferencing ptr1 once gives us a pointer to a const char, but is not itself const. However, ptr3 is const. So why doesn't the compiler generate a warning? Am I missing something, or is there a reason it shouldn't be generating a warning?
autois a keyword in C - or don't use it. C++11 has defined a use for it, but in C99 it is noise. - Jonathan Leffler