Course contentsShow
← C
Lesson 500 of 1,2197. PointersFree lesson

Concept of double indirection

Concept of double indirection

What you'll learn: How to use a pointer that stores the memory address of another pointer to create multiple levels of redirection.

The box within a box

So far, you’ve learned that a pointer is a variable that holds the address of a value. If a regular variable is a "box" containing a number, a pointer is a "note" telling you which box to open.

Double indirection (or a pointer-to-pointer) adds one more layer. Imagine you have a locked treasure chest.

  1. You have a Key (the double pointer).
  2. The Key opens a Drawer (the single pointer).
  3. Inside that Drawer is a Map that tells you exactly where the Treasure (the actual data) is hidden.

In C, we denote this with two asterisks: int **ptrToPtr;.

Why follow the trail?

You might wonder why we need this complexity. It is primarily used when you want to change where a pointer is looking from inside a function, or when dealing with grids of data.

Think of a double pointer as a "manager." If a single pointer is an employee pointing at a task, the double pointer is the manager who can tell that employee to stop looking at Task A and start looking at Task B instead.

Seeing it in code

Here is how the layers look in practice. Notice how we use two asterisks to "hop" twice to get to the final value.

#include <stdio.h>

int main() {
    int treasure = 500;
    
    // 1. A normal pointer (points to the treasure)
    int *ptr = &treasure;
    
    // 2. A pointer-to-pointer (points to the address of ptr)
    int **ptrToPtr = &ptr;

    printf("Value of treasure: %d\n", treasure);
    
    // Single de-reference (*ptr) gets the value
    printf("Value via ptr: %d\n", *ptr);
    
    // Double de-reference (**ptrToPtr) hops twice to get the value
    printf("Value via ptrToPtr: %d\n", **ptrToPtr);

    return 0;
}

How to read the syntax

When you see **ptrToPtr, read it from right to left:

  • ptrToPtr: The address of the pointer.
  • *ptrToPtr: The address stored inside that pointer (the first hop).
  • **ptrToPtr: The actual integer value at the final destination (the second hop).

Each * is essentially a command saying, "Go to the address written here." With double indirection, you are simply following two sets of directions to find your data.

Key takeaway

A pointer-to-pointer (**) stores the memory address of another pointer, allowing you to manipulate where that pointer is looking.