Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print the address or pointer for value in C

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;  
like image 403
Frank V Avatar asked Jun 28 '09 22:06

Frank V


People also ask

How do you print the address stored in a pointer in C?

How do I print the address stored in the pointer in C++? int *ptr = &var; printf("%p", ptr); That will print the address stored in ptr will be printed.

How do you get the value of a pointer in C?

Declare a pointer variable with the same type as the normal variable. Initialize the pointer variable with the address of normal variable. Access the value of the variable by using asterisk (*) - it is known as dereference operator.

Does a pointer point to an address or a value?

Put another way, the pointer does not hold a value in the traditional sense; instead, it holds the address of another variable. A pointer "points to" that other variable by holding a copy of its address. Because a pointer holds an address rather than a value, it has two parts. The pointer itself holds the address.

What is the value of a pointer in C?

The actual data type of the value of all pointers, whether integer, float, character, or otherwise, is the same, a long hexadecimal number that represents a memory address. The only difference between pointers of different data types is the data type of the variable or constant that the pointer points to.


2 Answers

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.

like image 52
stefanB Avatar answered Oct 10 '22 00:10

stefanB


What you have is correct. Of course, you'll see that emp1 and item1 have the same pointer value.

like image 27
Don Neufeld Avatar answered Oct 09 '22 22:10

Don Neufeld