Search code examples
c++type-conversiontypecast-operator

about c++ cast question


#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;
    }
}

In this code, what does this line mean?

int first = *(int*)first_arg;

I thinks it's typecasting. But, from

a pointer to int to a pointer to int

little confused here. Thanks

?


Solution

  • first_arg is declared as a void*, so the code is casting from void* to int*, then it de-references the pointer to get the value pointed from it. That code is equal to this one:

    int first = *((int*) first_arg);
    

    and, if it is still not clear:

    int *p = (int *) first_arg;
    int first = *p;