1

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?

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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

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

1 Comment

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.