Reputation: 83
Because I have been confused, Can someone explain me what *(int*)a
or *(int*)b
is in the following example, type casting or some complex pointer declaration? I need to use bsearch function. Thanks
int cmpfunc(const void * a, const void * b)
{
return ( *(int*)a - *(int*)b );
}
Upvotes: 0
Views: 448
Reputation: 6994
A more readable version without explicit (and potentially unsafe) casts would be
int cmpfunc(const void * a_, const void * b_)
{
int const *a = a_;
int const *b = b_;
return *a - *b;
}
Upvotes: 0
Reputation: 224437
This is a cast. a
, which is of type const void *
, is first cast to an int *
, then that int *
is dereferenced to read an int
.
Breaking it down:
a
: type const void *
(int *)a
: type int *
*(int *)a
: type int
.The reason this is done is because a function of type int (*)(const void *, const void *)
is required to be passed to the bsearch
and qsort
functions as a callback. Defining the arguments as const void *
allows qsort
to sort any arbitrary data by having the callback function cast the arguments to the appropriate type.
Upvotes: 3