C Language | Pointers | Pointers to Pointers

A pointer that stores an address is also a type of variable, and the pointer itself has an address. You can use the address operator to obtain a pointer’s address, creating a pointer to a pointer.

Pointer Addresses

A pointer is a type of variable that stores a numeric value representing a referenced address. Because a pointer is a variable, it also has its own address. In other words, you can create a pointer to a pointer by storing the address of one pointer in another pointer.

A pointer to a pointer references another pointer, which can then reference the original variable. Multiple indirection is an important part of understanding pointers. To declare a pointer to a pointer, add another asterisk (*).

Declaring a Pointer to a Pointer

type **variableName;

To perform multiple indirection, specify the indirection operator (*) once for each level of reference. Excessive indirection can affect performance and should be avoided when it serves no purpose. However, a pointer to a pointer is useful when another function needs to modify a pointer owned by the caller.

#include <stdio.h>

int main() {
  int iVariable = 100;
  int *ip = &iVariable;
 int **ipp = &ip;

  printf("--values represented by pointer ip--\n");
  printf("address = %p\n" , &ip);
 printf("stored address = %p\n" , ip);
 printf("content at stored address = %d\n\n" , *ip);

  printf("--values represented by pointer-to-pointer ipp--\n");
  printf("stored value = %p\n" , ipp);
  printf("content at stored address = %p\n" , *ipp);
 printf("content at address stored by stored address = %d\n", **ipp);

 return 0;
}

Code 1 defines iVariable, which stores the integer 100; the pointer ip, which stores the address of iVariable; and the pointer to a pointer ipp, which stores the address of ip. The program prints several values to demonstrate the relationship between a pointer and a pointer to a pointer. The displayed addresses differ each time the program runs.

The address operator (&) obtains the address of pointer ip. Because ipp stores this value, the address of ip and the value stored in ipp are the same. Dereferencing ipp refers to the value stored by ip. This is why the content at the address stored in ipp matches the address stored in ip.

To access the original variable through a pointer to a pointer, perform multiple indirection. Writing **ipp follows the address stored in ipp, which is ip, and then the address stored in ip, which is iVariable.