开发者

Problem using void pointer as a function argument

I can't understand this result...

The code:

void foo(void * key, size_t key_sz) {
    HashItem *item = malloc(sizeof(HashItem));

    printf("[%d]\n", (int)key);

    ...

    item->key = malloc(key_sz);
    memcpy(item->key, key, key_sz);
}

void bar(int num) {
    foo(&num, sizeof(int));
}

And I do开发者_高级运维 this call: bar(900011009);

But the printf() output is:

[-1074593956]

I really need key to be a void pointer, how can I fix this?


I think you need this:

printf("[%d]\n", *(int*)key); 

The key is a void pointer to the int, so you first need to cast to an int pointer, then dereference to get the original int.


If you cast the pointer to int, you are getting the address as the value. You need to dereference void pointers like any other. Only you cannot directly dereference void *, so you must first cast it to a pointer of the correct type, here int *. Then dereference that pointer, i.e. *((int *)key) (extra parentheses to clarify the precedence).

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜