开发者

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 < seco开发者_运维问答nd )
    {
        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

?


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;


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


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.


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.


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜