C Programming: Memory, Pointers and the Stack · Pointers

Pointers to Pointers

A pointer can point to another pointer. Follow the chain with ** to reach the value at the end.

pointer_to_pointer.c

#include <stdio.h>

void reset(int **pp) {
    **pp = 0;                 /* changes the int at the end of the chain */
}

int main(void) {
    int value = 9;
    int *p = &value;
    int **pp = &p;            /* a pointer to a pointer */
    int seen = **pp;
    reset(pp);
    printf("%d %d\n", seen, value);
    return 0;
}

Step by step

  1. value is created on the stack with the value 9.
  2. p is created on the stack with the value → value.
  3. pp holds the address of p, which holds the address of value.
  4. **pp follows both links: 9.
  5. C calls reset(), with pp = → p. It gets its own variables on the stack.
  6. In reset, **pp reaches main's value through two pointers.
  7. reset() has finished, so its variables are gone.
  8. It prints 9 0.
  9. The method returns 0.
  10. seen 9, value 0.