1

I want to pass a pointer to a variable. Sometimes it would be an integer and sometimes maybe a character. In the example below i pass the pointer p to CreateObject but when i try to retrieve the value of the variable the pointer points to i get an awkward result:

int i =0;
int *p = malloc(sizeof(int));
*p = i;

ObjectP object = CreateObject(p);

Say i want to cast it back to an int and display it:

void CreateObject(void *key)
{
   printf("%d\n", (int)key);
}

I get: 160637064 instead of 0. What am i getting instead of the integer i assigned previously and how do i retrieve it instead of the current value?

1
  • 1
    And, out of curiosity, how do you plan to distinguish the size of the element passed? Another parameter? Commented Dec 25, 2012 at 13:37

3 Answers 3

6

This:

(int) key

is not dereferencing the pointer to access the data it points at, it's re-interpreting the pointer value (the address) itself as the integer.

You need:

printf("%d\n", *(int *) key);
Sign up to request clarification or add additional context in comments.

Comments

3

You're typecasting a pointer to an integer. This means that you simply get the address. After all, a pointer is just an address.

You probably want to dereference the pointer instead of casting it. *(int*)key would do that.

Comments

3

You're printing the pointer, ie. the address, not the value that it's pointing to.

Use this to print the value:

void CreateObject(void *key)
{
   printf("%d\n", *(int*)key);
}

Comments

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.