Back to Blog

C in 100 Seconds: Double Pointers | Episode 29

Daryl WongDaryl Wong

Video: C in 100 Seconds: Double Pointers — Pointer to Pointer | Episode 29 by Taught by Celeste AI - AI Coding Coach

Watch full page →

Double Pointers — Pointer to Pointer

C in 100 Seconds, Episode 29


A double pointer holds the address of another pointer. One level of indirection gives you the pointer. Two levels give you the value. The real use case: letting a function allocate memory that the caller can use.

The Pointer Chain

int x = 42;
int *p = &x;
int **pp = &p;

x is the value. p points to x. pp points to p. Dereference once with *pp to get p. Dereference twice with **pp to get x.

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

Allocating in a Function

The real reason double pointers exist. If a function needs to malloc memory and the caller needs to see the result, pass a pointer to the pointer:

void allocate(int **ptr, int value) {
  *ptr = malloc(sizeof(int));
  **ptr = value;
}

int *data = NULL;
allocate(&data, 99);
printf("allocated: %d\n", *data);  // 99
free(data);

*ptr changes where the caller's pointer points. **ptr sets the value at that location. Without the double pointer, the function would only modify a local copy.

When You Need Double Pointers

  • Allocating in functions — malloc inside a function, caller uses the result
  • Modifying a pointer — changing what a pointer points to from another function
  • 2D dynamic arrays — array of pointers to arrays
  • Linked list operations — inserting at head requires Node **head

Full Code

#include <stdio.h>
#include <stdlib.h>

void allocate(int **ptr, int value) {
  *ptr = malloc(sizeof(int));
  **ptr = value;
}

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

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

  int *data = NULL;
  allocate(&data, 99);
  printf("\nallocated: %d\n", *data);
  free(data);

  return 0;
}

Next episode: Void Pointers — generic programming in C.

Student code: github.com/GoCelesteAI/c-in-100-seconds/episode29