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 ???.
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.
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.
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).
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.
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; 
                        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); 
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With