pointer to pointer

As we know, a pointer variable stores the address of another variable. In this, a pointer variable which stores the address of a other variable than before, another pointer-variable stores the address of this pointer-variable.

pointer-to-pointer

There is syntex below

Data type **pointer-variable;

Example:-

int **ptr;

 

How to access a pointer-variable address?

First of all, we declare a pointer-variable,

int *ptr1;

then declare a pointer-to-pointer variable and,

int **ptr2;

then assign the pointer-variable ptr1 to the pointer-variable ptr2, such as

ptr2 = &ptr1;

Let’s understand this with the help of a program

In the program, the address of x variable is stored in one pointer-variable ptr1 while the address of this pointer-variable ptr1, is stored in another pointer variable ptr2. When this program executes, pointer-variable ptr1 will print the address of variable x. After this the address of this pointer-variable ptr1, will print by another pointer variable ptr2.

#include<iostream.h>
#include<conio.h>
void main()
{
   int x=6;
   int *ptr1,**ptr2;

   ptr1 = &x; 
   ptr2 = &ptr1;

   clrscr();

   cout<<"Values are:\n";
   cout<<"ptr1: "<<*ptr1<<" "<<**ptr2<<endl;

   cout<<"\nAddress of:\n";

   cout<<"*ptr2: "<<*ptr2<<endl;
   cout<<"ptr1: "<<ptr1<<endl;
   cout<<"ptr2: "<<ptr2;

 getch();
}
OUTPUT:-
ptr1: 6 6
Address of:

*ptr2: 0x8f2bfff2
ptr1: 0x8f2bfff2
ptr2: 0x8f2bfff0

Explanation:-

As you can see *ptr2 and ptr1 are displaying the same address in output This is because pointer variable ptr1 is printing the address of variable x. But *ptr2 is displaying store data in pointer variable ptr1 which is the address of variable x.

more about pointer


previous-union in C++

next-Memory Management and Types