This code snippet hand copied from a book I am reading:
/* scmp: string compare of *p1 and *p2 */
int scmp(const void *p1, const void *p2)
{
char *v1, *v2;
v1 = *(char **) p1;
v2 = *(char **) p2;
return strcmp(v1, v2);
}
This function is used with qsort to sort an array of strings. The point I don’t understand is, why v1 = *(char **) p1; instead of just v1 = (char *) p1; or wouldn’t even this work; v1 = p1;? I guess compiler should automatically typecast that assigment. Or even, consider this:
/* scmp: string compare of *p1 and *p2 */
int scmp(const void *p1, const void *p2)
{
return strcmp(p1, p2);
}
I think (I might be awfully wrong) compiler is supposed to typecast p1 and p2 into char * since it’s what strcmp(char *, char *) expects.
To sum up, the question is why v1 = *(char **) p1 ?
qsortpasses to the comparing function a pointer to the elements it has to compare; since in C there are no templates, this pointer is just brutally cast to aconst void *(void *in C just means “this is some kind of pointer”, and to do something on it you must cast it back to its actual type).Now, if you are sorting an array of strings, each element you have to compare is a
char *; butqsortpasses to the comparison function a pointer to each element, so what yourscmpreceives is actually achar **(a pointer to a pointer to the first character of the string), casted to aconst void *because the signature of the comparison function says so.So, to get your
char *, you have first to convert the parameters to their actual type (char **), and then dereference this pointer to get the actualchar *you want to compare.(although, it would be more correct from a const-correctness point of view to cast to
const char **)