David Degea
David Degea

Reputation: 1398

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

?

Upvotes: 4

Views: 242

Answers (5)

Juliano
Juliano

Reputation: 41387

There are already many answers to your question, this is more like a comment, something that you will inevitably learn in your quest on mastering C and C++.

Your function is too long. From its name, I predict what you really need is:

int int_sorter( const void *first_arg, const void *second_arg )
{
    return *(int*)first_arg - *(int*)second_arg;
}

Upvotes: 0

Jonathan Sterling
Jonathan Sterling

Reputation: 18375

Let's think about it in steps.

void *vptr = first_arg;
int *iptr = (int *)first_arg; // cast void* => int*
int i = *iptr; // dereference int* => int

So, you're specifying the type of data the pointer points to, and then dereferencing it.

Upvotes: 1

BlackBear
BlackBear

Reputation: 22979

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;

Upvotes: 7

Alok Save
Alok Save

Reputation: 206528

It is casting a void pointer to a integer pointer and then dereferencing it.

Upvotes: 1

karlphillip
karlphillip

Reputation: 93410

int first = *(int*)first_arg;

It's the same as:

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

That first line does 2 things: it casts the void pointer to an int* and access that memory location to retrieve the value that's there.

Upvotes: 0

Related Questions