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

Declaring `int **pp`

Declaring int **pp

What you'll learn: How to create a variable that stores the memory address of another pointer.

The "Address Book" Analogy

Think of a standard variable as a house. A pointer is like a piece of paper with that house’s address written on it. But what if you put that piece of paper inside a specific drawer? To find the house, you first need to find the drawer.

A pointer to a pointer is that drawer. It doesn't hold a number or a house address directly; it holds the address of the paper that has the address. In C, we represent this "extra layer" by adding a second asterisk.

The Double Asterisk Syntax

When we declare int *p, we are telling C: "This variable holds the location of an integer." When we declare int **pp, we are saying: "This variable holds the location of a variable that holds the location of an integer."

Here is how the hierarchy looks in code:

#include <stdio.h>

int main() {
    int value = 42;        // A normal integer
    int *p = &value;       // A pointer to the integer
    int **pp = &p;         // A pointer to the pointer

    // Printing the values
    printf("Value: %d\n", value);   // Output: 42
    printf("Pointer p: %p\n", p);   // Output: Address of 'value'
    printf("Pointer pp: %p\n", pp); // Output: Address of 'p'

    return 0;
}

Why do we need this?

You might wonder why we would ever want to be so indirect. While it seems like extra work, it is essential for specific tasks. The most common use is when you want a function to change where a pointer points.

Just as you pass a variable's address (&x) to a function if you want to change its value, you must pass a pointer's address (&p) if you want to change which memory location that pointer is looking at. This is frequently used in complex data structures like linked lists or when managing dynamic 2D arrays.

Key takeaway

A ** declaration adds a layer of indirection, allowing a variable to store the memory address of another pointer.