B
Bob
I'm reading from
http://www.eskimo.com/~scs/cclass/int/sx10b.html
about qsort. It says
----------
The Standard C library contains a general-purpose sort function, qsort
(declared in <stdlib.h>), which can sort any type of data (not just
strings). It's a bit trickier to use (due to this generality), and you
almost always have to write an auxiliary comparison function. For
example, due to the generic way in which qsort calls your comparison
function, you can't use strcmp directly even when you're sorting
strings and would be satisfied with strcmp's ordering. Here is an
auxiliary comparison function and the corresponding call to qsort which
would behave like our earlier call to stringsort(array1, 4, strcmp) :
/* compare strings via pointers */
int pstrcmp(const void *p1, const void *p2)
{
return strcmp(*(char * const *)p1, *(char * const *)p2);
}
....
qsort(array1, 4, sizeof(char *), pstrcmp);
----------
Now my question is how to "think about" the line
strcmp(*(char * const *)p1, *(char * const *)p2);
To make it easier I disregard const so I end up with
strcmp(*(char **)p1, *(char **)p2);
Now char ** is a type. What type? A pointer to a charpointer, but since
a charpointer is a string, the type is a pointer to a string. So p1 is
cast into a pointer to a string. Now dereferencing this with a * gives
a string. And that is good because strcmp takes two strings as
arguments.
I'm uncertain if I reason correctly or if I should think differently.
Bob
http://www.eskimo.com/~scs/cclass/int/sx10b.html
about qsort. It says
----------
The Standard C library contains a general-purpose sort function, qsort
(declared in <stdlib.h>), which can sort any type of data (not just
strings). It's a bit trickier to use (due to this generality), and you
almost always have to write an auxiliary comparison function. For
example, due to the generic way in which qsort calls your comparison
function, you can't use strcmp directly even when you're sorting
strings and would be satisfied with strcmp's ordering. Here is an
auxiliary comparison function and the corresponding call to qsort which
would behave like our earlier call to stringsort(array1, 4, strcmp) :
/* compare strings via pointers */
int pstrcmp(const void *p1, const void *p2)
{
return strcmp(*(char * const *)p1, *(char * const *)p2);
}
....
qsort(array1, 4, sizeof(char *), pstrcmp);
----------
Now my question is how to "think about" the line
strcmp(*(char * const *)p1, *(char * const *)p2);
To make it easier I disregard const so I end up with
strcmp(*(char **)p1, *(char **)p2);
Now char ** is a type. What type? A pointer to a charpointer, but since
a charpointer is a string, the type is a pointer to a string. So p1 is
cast into a pointer to a string. Now dereferencing this with a * gives
a string. And that is good because strcmp takes two strings as
arguments.
I'm uncertain if I reason correctly or if I should think differently.
Bob