C Tutorial 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 <stdio.h>
 
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
  printf("Checking ptr1 and *ptr2 \n");
  printf("*ptr2 : %p\n", *ptr2);
  printf("ptr1 : %p\n", ptr1);

  //checking Var, *ptr1 and **ptr2
  printf("\nChecking Var, *ptr1 and **ptr2 \n");
  printf("**ptr2 : %i\n", **ptr2);
  printf("*ptr1 : %i\n", *ptr1);
  printf("Var : %i\n", Var);
  return 0;
}

The output of the above code will be:

Checking ptr1 and *ptr2 
*ptr2 : 0x7ffe5bd1ac64
ptr1 : 0x7ffe5bd1ac64

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 <stdio.h>
 
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++) {
    printf("*(*p2 + %i) = %i\n", i, *(*p2+i));
  }
  return 0;
}

The output of the above code will be:

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

❮ C - Pointers

5