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
?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…