Reputation: 2777
#include <stdlib.h>
int int_sorter( const void *first_arg, const void *second_arg )
{
int first = *(int*)first_arg;
int second = *(int*)second_arg;
if ( first < second )
{
return -1;
}
else if ( first == second )
{
return 0;
}
else
{
return 1;
}
}
int main()
{
int array[10];
int i;
/* fill array */
for ( i = 0; i < 10; ++i )
{
array[ i ] = 10 - i;
}
qsort( array, 10 , sizeof( int ), int_sorter );
for ( i = 0; i < 10; ++i )
{
printf ( "%d\n" ,array[ i ] );
}
}
I don't understand this line :
int first = *(int*)first_arg;
could anyone help me? explain it? thank you very much!!!
Is this a casting? explicit cast, from void*
to int
? but why we need ampersand outside ()
?
Upvotes: 0
Views: 241
Reputation: 6834
int first = *(int*)first_arg;
is the same as:
int* ptrToFirst = (int*)first_arg;
This is an explicit cast from const void* to int.
int first = *ptrToFirst;
Here the *
is the dereferencing operator. This is pronounced 'star'.
This is an 'ampersand': '&'.
Why are we doing this? qsort() needs to have the callback determine the ordering. By passing the values indirectly as const void pointers, the arguments to the callback have fixed size even though the values could be any size. That is why the values need cast back in the callback.
Upvotes: 3
Reputation: 7953
You are first casting the void pointer to an int pointer:
(int*)first_arg
And then dereferencing the pointer: *(int*)first_arg
to get the integer it points to. This is then assigned to an integer variable.
Upvotes: 9