Print the address or pointer for value in C

Frank V picture Frank V · Jun 29, 2009 · Viewed 232.4k times · Source

I want to do something that seems fairly simple. I get results but the problem is, I have no way to know if the results are correct.

I'm working in C and I have two pointers; I want to print the contents of the pointer. I don't want to dereference the pointer to get the value pointed at, I just want the address that the pointer has stored.

I wrote the following code and what I need to know is if it is right and if not, how can I correct it.

/* item one is a parameter and it comes in as: const void* item1   */
const Emp* emp1 = (const Emp*) item1; 

printf("\n comp1-> emp1 = %p; item1 = %p \n", emp1, item1 );

While I'm posting this (and the reason it is important that it is correct) is that I eventually need to do this for a pointer-to-a-pointer. That is:

const Emp** emp1 = (const Emp**) item1; 

Answer

stefanB picture stefanB · Jun 29, 2009

To print address in pointer to pointer:

printf("%p",emp1)

to dereference once and print the second address:

printf("%p",*emp1)

You can always verify with debugger, if you are on linux use ddd and display memory, or just plain gdb, you will see the memory address so you can compare with the values in your pointers.