문제

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

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top