C Programming - Beginner to Brilliance / Pointers in C

Pointers to Pointers

🧠 What is a Pointer to a Pointer?

A pointer to a pointer is exactly what it sounds like:

It is a variable that stores the address of another pointer, which in turn stores the address of a variable.

It’s like two levels of indirection.


πŸ“ Basic Idea:

Let’s take a regular variable:

int x = 10;       // x holds value 10
int *p = &x;      // p holds address of x
int **pp = &p;    // pp holds address of p

So:

  • x β†’ actual integer value

  • p β†’ pointer to x

  • pp β†’ pointer to pointer of x



βœ… Example Code

#include <stdio.h>

int main() {
    int x = 42;
    int *p = &x;
    int **pp = &p;

    printf("x = %d\\n", x);       // 42
    printf("*p = %d\\n", *p);     // 42
    printf("**pp = %d\\n", **pp); // 42

    return 0;
}
x = 42
*p = 42
**pp = 42

πŸ” Accessing Values

Expression

Meaning

x

Actual value

p

Address of x

*p

Value of x

pp

Address of p

*pp

Value stored in p (i.e., address of x)

**pp

Final value of x


πŸ’‘ When is Pointer to Pointer Used?

βœ… Dynamic 2D Arrays

int **matrix;

Used to create a matrix (array of arrays) dynamically using malloc.


βœ… Modifying a Pointer from Function

If you want to change the address stored in a pointer inside a function, pass a pointer to pointer.

void allocate(int **p) {
    *p = malloc(sizeof(int));
    **p = 100;
}

βœ… Command Line Arguments

int main(int argc, char **argv)

Here, argv is a pointer to an array of character pointers, i.e., char **.


πŸ” Pointer to Pointer with Functions (Full Example)

#include <stdio.h>

void update(int **ptr) {
    static int val = 99;
    *ptr = &val;  // update original pointer to point to new value
}

int main() {
    int x = 10;
    int *p = &x;
    int **pp = &p;

    printf("Before: *p = %d\\n", *p);  // 10
    update(pp);
    printf("After : *p = %d\\n", *p);  // 99

    return 0;
}

🧠 Tip to Understand:

Think of pointers as addresses and * as the key to open the address and see what's inside.

So:

**pp
β†’ first *pp = p
β†’ second *p = x