Reputation:
int compare (const void * a, const void * b)
{
return ( *(int*)a - *(int*)b );
}
I don't understand expression *(int*)a
?
Upvotes: 0
Views: 308
Reputation: 3399
(int*)a
converts void pointer to int type pointer. *(int*)a
takes the value that the pointer points to.
Upvotes: 0
Reputation: 409176
A void *
pointer is a generic pointer, it can point to anything, but as the compiler doesn't know exactly what it's pointing to you have to tell the compiler what exactly it's pointing to. This "telling" is what the cast does: (int *) a
tells the compiler that a
is actually pointing to an int
.
Then the code is simply using the dereference operator (unary *
) to get the value of where a
is pointing and using that in a normal subtraction expression.
Upvotes: 8
Reputation: 15229
(int*)a
casts a
to int*
. Simply dereferencing a
doesn't work because *a
would have type void
, which is not allowed.
Furthermore, this is somewhat unsafe here as a
is passed as const
and the caller expects *a
not to be changed. OK, a
isn't changed indeed but such an explicit conversion should be a rarity.
The additional dereferencing "gets" the value a
points to. In the end, compare
returns 0
if both data are equal.
Upvotes: 4