views:

144

answers:

2

Hi,

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?

+3  A: 

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.

Saxon Druce
Yeah, I tried `(int*)*key` but didn't work and `*(int*)key` never occurred to me.
Nazgulled
+2  A: 

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 illustrate the effect).

Arkku
Yeah, I tried `(int*)*key` but didn't work and `*(int*)key` never occurred to me.
Nazgulled