← Back to C Course | Chapter 7: Pointers | Lesson 6 of 9

C Double Pointers

What is a Double Pointer?

You can chain this indirection further -- a triple pointer stores the address of a double pointer -- but in practice, C code rarely goes beyond two levels because the added complexity outweighs the benefit.

Example: What is a Double Pointer?

c
#include <stdio.h>
int main() {
	int x = 5;
	int *ptr = &x;
	int **pptr = &ptr;
	printf("%d", **pptr);
	return 0;
}

Declaring Double Pointers

int **pptr declares pptr as a pointer to a pointer to an int; the type must match at every level, so you can't assign the address of a plain int pointer to a variable declared with three asterisks.

Example: Declaring Double Pointers

c
#include <stdio.h>
int main() {
	int x = 5;
	int *ptr = &x;
	int **pptr = &ptr;
	printf("%d", **pptr);
	return 0;
}

Initializing and Referencing

A typical setup looks like: int x = 5; int *ptr = &x; int **pptr = &ptr -- pptr now holds the address where ptr itself is stored, one level of indirection above x.

Example: Initializing and Referencing

c
#include <stdio.h>
int main() {
	int x = 5;
	int *ptr = &x;
	int **pptr = &ptr;
	printf("%d", *ptr);
	return 0;
}

Double Dereferencing ()

Given the setup above, *pptr yields ptr (the address of x), and **pptr yields the value of x itself (5) -- each asterisk peels back exactly one layer of indirection.

Example: Double Dereferencing ()

c
#include <stdio.h>
int main() {
	int x = 5;
	int *ptr = &x;
	int **pptr = &ptr;
	printf("%d", **pptr);
	return 0;
}

Practical Uses of Double Pointers

This is essential when a function needs to modify what a pointer points to (not just the value at that address) -- for example, a function that allocates memory and needs the caller's pointer variable itself to be updated to point at the new block.

Example: Practical Uses of Double Pointers

c
#include <stdio.h>
void allocate(int **out) {
	static int value = 99;
	*out = &value;
}
int main() {
	int *result;
	allocate(&result);
	printf("%d", *result);
	return 0;
}

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.