Can a pointer variable contain the address of another pointer variable?

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

+4
source share
6 answers

Of course, a pointer to a pointer.

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

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

+10
source

Yes, but it must be of the correct type. In your example, int *ptr,*ptr1; both ptr and ptr1 are of type "pointer to int ", which can only point to int , not to a pointer. If you declare int *ptr, **ptr1; , then ptr1 is of type "pointer to int * " and, therefore, can point to ptr .

+3
source

Here is an example 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 .

+1
source

A pointer to a 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 a generic pointer)

0
source

There are two answers, and they are 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;

Pay attention to an additional asterisk.

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

Yes, pls see the following code. I hope this serves your purpose

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

Here ptr1 is the only pointer, but behaves like a double pointer

0
source

Source: https://habr.com/ru/post/1391750/


All Articles