The following code is from The Practice of Programming:
int scmp(const void *p1, const void *p2)
{
char *v1, *v2;
v1 = *(char **) p1;
v2 = *(char **) p2;
return strcmp(v1, v2);
}
I don’t understand why using the expression *(char **) p1. Can we use (char *)p1 instead?
What is the difference between them?
Thanks!
No. The
(char **)is a type cast, and the unary*which precedes the cast dereferences the pointer. If you simply takev1 = (char *) p1, thenv1will be set equal top1, when what you want is forv1to be equal to thechar*to whichp1points.