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

Accessing data through double dereference

Accessing data through double dereference

What you'll learn: How to reach a final value by following a chain of two memory addresses using the double asterisk operator.

The Chain of Custody

In C, a pointer holds a memory address. A pointer to a pointer (a "double pointer") simply holds the address of another pointer. To get to the actual data at the very end of this chain, you have to "unlock" two doors. This process is called double dereferencing.

Think of it like a scavenger hunt:

  1. You have a slip of paper (the double pointer).
  2. The paper tells you where to find a locked box (the first pointer).
  3. Inside that box is a key (the second address).
  4. That key opens a safe containing the gold (the actual data).

Using the Double Asterisk

To reach the data, we use the * operator twice. Each * represents one step of following the address to see what is stored there.

#include <stdio.h>

int main() {
    int gold = 100;        // The actual value
    int *box = &gold;      // A pointer to the value
    int **paper = &box;    // A pointer to the pointer

    // Accessing the value
    printf("Value of gold: %d\n", gold);
    
    // Single dereference: Following 'paper' leads us to the address stored in 'box'
    // Double dereference: Following 'paper' then following 'box' leads to 'gold'
    printf("Value via double dereference: %d\n", **paper);

    // We can even change the value from the paper!
    **paper = 500;
    printf("New value of gold: %d\n", gold);

    return 0;
}

How the Computer Sees It

When you write **paper, the computer performs two distinct moves:

  • First *: It looks at the address stored in paper. It travels there and finds the pointer box.
  • Second *: It looks at the address stored inside box. It travels there and finally arrives at the integer gold.

If you only used one asterisk (*paper), you would be looking at the memory address of the box, not the gold itself. By using two, you tell C to follow the trail all the way to the finish line. This is essential when you need to modify where a pointer is pointing from inside a function, or when dealing with complex grids of data.

Key takeaway

Double dereferencing (**) follows two consecutive memory addresses to access or modify the original value at the end of the chain.