rfgamaral
rfgamaral

Reputation: 16842

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?

Upvotes: 1

Views: 6050

Answers (2)

Arkku
Arkku

Reputation: 42109

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).

Upvotes: 2

Saxon Druce
Saxon Druce

Reputation: 17624

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.

Upvotes: 4

Related Questions