C++ Tutorial C++ Advanced C++ References

C++ - Pointer to Pointer (Double Pointer)



A pointer in C++ contains the address of a variable and a pointer to pointer contains the address of the first pointer as shown in the diagram below:

Pointer to pointer

The above diagram shows the memory representation of a pointer to pointer. The first pointer stores the address of the variable and the second pointer stores the address of the first pointer.

Declaring Pointer to Pointer is similar to declaring pointer with additional asterisk * before the name of pointer. For example, the syntax to declare a pointer to pointer of type int is given below:

int **ptr;

Example:

In the example below, the memory representation of a pointer to pointer is illustrated.

#include <iostream>
using namespace std;
 
int main (){
  int Var = 10;

  //pointer to Var
  int *ptr1;
  ptr1 = &Var;

  //pointer to pointer of Var
  int **ptr2;
  ptr2 = &ptr1;

  //checking ptr1 and *ptr2
  cout<<"Checking ptr1 and *ptr2 \n";
  cout<<"*ptr2 : "<<*ptr2<<"\n";
  cout<<"ptr1 : "<<ptr1<<"\n";

  //checking Var, *ptr1 and **ptr2
  cout<<"\nChecking Var, *ptr1 and **ptr2 \n";
  cout<<"**ptr2 : "<<**ptr2<<"\n";
  cout<<"*ptr1 : "<<*ptr1<<"\n";
  cout<<"Var : "<<Var<<"\n";
  return 0;
}

The output of the above code will be:

Checking ptr1 and *ptr2 
*ptr2 : 0x7ffd077258f4
ptr1 : 0x7ffd077258f4

Checking Var, *ptr1 and **ptr2 
**ptr2 : 10
*ptr1 : 10
Var : 10

Example:

Consider on more example where double pointer is used to access the elements of an array for illustration purpose.

#include <iostream>
using namespace std;
 
int main (){
  int Arr[3] = {10, 20, 30};
  int *p1, **p2;

  p1 = Arr;        //pointing to Arr[0]  
  p2 = &p1;        //pointing to Arr[0] 

  for(int i = 0; i<3; i++) {
    cout<<"*(*p2 + "<<i<<") = "<<*(*p2+i)<<"\n";
  }
  return 0;
}

The output of the above code will be:

*(*p2 + 0) = 10
*(*p2 + 1) = 20
*(*p2 + 2) = 30

❮ C++ - Pointers

5