Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

?

like image 612
David Degea Avatar asked Feb 23 '23 08:02

David Degea


1 Answers

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;
like image 183
BlackBear Avatar answered Mar 06 '23 17:03

BlackBear