Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get address of a pointer in c/c++?

Tags:

c++

c

How to get address of a pointer in c/c++?

Eg: I have below code.

int a =10; int *p = &a; 

So how do I get address of pointer p? Now I want to print address of p, what should I do?

print("%s",???) what I pass to ???.

like image 572
Trung Nguyen Avatar asked Mar 07 '14 12:03

Trung Nguyen


People also ask

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

You can print a pointer value using printf with the %p format specifier. To do so, you should convert the pointer to type void * first using a cast (see below for void * pointers), although on machines that don't have different representations for different pointer types, this may not be necessary.

Do pointers have addresses?

Because a pointer holds an address rather than a value, it has two parts. The pointer itself holds the address. That address points to a value. There is the pointer and the value pointed to.

How do I find the value of a pointer?

To get the value pointed to by a pointer, you need to use the dereferencing operator * (e.g., if pNumber is a int pointer, *pNumber returns the value pointed to by pNumber . It is called dereferencing or indirection).

What is pointer value and address?

A pointer is a variable whose value is the address of another variable, i.e., direct address of the memory location. Like any variable or constant, you must declare a pointer before using it to store any variable address.


2 Answers

To get the address of p do:

int **pp = &p; 

and you can go on:

int ***ppp = &pp; int ****pppp = &ppp; ... 

or, only in C++11, you can do:

auto pp = std::addressof(p); 

To print the address in C, most compilers support %p, so you can simply do:

printf("addr: %p", pp); 

otherwise you need to cast it (assuming a 32 bit platform)

printf("addr: 0x%u", (unsigned)pp); 

In C++ you can do:

cout << "addr: " << pp; 
like image 103
Loghorn Avatar answered Sep 17 '22 09:09

Loghorn


int a = 10; 

To get the address of a, you do: &a (address of a) which returns an int* (pointer to int)

int *p = &a; 

Then you store the address of a in p which is of type int*.

Finally, if you do &p you get the address of p which is of type int**, i.e. pointer to pointer to int:

int** p_ptr = &p; 

just seen your edit:

to print out the pointer's address, you either need to convert it:

printf("address of pointer is: 0x%0X\n", (unsigned)&p); printf("address of pointer to pointer is: 0x%0X\n", (unsigned)&p_ptr); 

or if your printf supports it, use the %p:

printf("address of pointer is: %p\n", p); printf("address of pointer to pointer is: %p\n", p_ptr); 
like image 20
zmo Avatar answered Sep 17 '22 09:09

zmo