sandbox
sandbox

Reputation: 2679

Can a Pointer variable holds the address of another Pointer Variable?

Is it possible to make a pointer variable hold the address of another pointer variable? eg:
int a; int *ptr,*ptr1; ptr=&a; ptr1=&ptr;

Upvotes: 4

Views: 3350

Answers (6)

Jonathan Wood
Jonathan Wood

Reputation: 67195

Sure, a pointer to a pointer.

int i;
int *pi = &i;
int **ppi = π

There is nothing particularly unusual about a pointer to a pointer. It's a variable like any other, and it contains the address of a variable like any other. It's just a matter of setting the correct type so that the compiler knows what to do with them.

Upvotes: 10

user966379
user966379

Reputation: 2983

Yes, Pls see the following code. I hope it will serve your purpose

int a = 4;
int *ptr = &a;
int *ptr1 = (int*)&ptr; 
cout << **(int**)ptr1;

Here ptr1 is single pointer but behaves as double pointer

Upvotes: 0

cctan
cctan

Reputation: 2023

Here's a sample showing what happens

int a = 13; 
int *ptr,
int **ptr1;       // ** means pointer to pointer
ptr = &a;   
ptr1 = &ptr;

cout << a;        //value of a  

cout << *ptr;     //ptr points to a, *ptr is value of a  
cout << **ptr1;   //same as above

cout << &ptr;     //prints out the address of ptr
cout << *ptr1;    //same as above

It works the same for int ***ptr, int ****ptr.

Upvotes: 1

rampion
rampion

Reputation: 89053

There's two answers here and they're both yes.

Two pointers can point to the same location

int b, *p1=&b, *p2=&b;
*p1 = 123;
*p2; // equals 123

You can also have a pointer to a pointer:

int x=2, y=3, *p=&x, **q=&p;

Note the extra asterisk.

**q; // equals 2
*q = &y;
**q; // equals 3
**q = 4;
  y; // equals 4

Upvotes: 0

asaelr
asaelr

Reputation: 5456

Pointer to pointer is possible (and very common), but int* may not be large enough to contain the address of another int*. use int**. (or void*, for generally pointer)

Upvotes: 0

R.. GitHub STOP HELPING ICE
R.. GitHub STOP HELPING ICE

Reputation: 215193

Yes, but it needs to have the right type. In your example int *ptr,*ptr1; both ptr and ptr1 have type "pointer to int", which can only point to an int, not a pointer. If you declare int *ptr, **ptr1;, then ptr1 has type "pointer to int *" and thus can point to ptr.

Upvotes: 3

Related Questions