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

C Pointer to Pointer

What is a Pointer to a Pointer?

This chain is exactly the mechanism argv uses in main(int argc, char **argv) -- argv is a pointer to an array of pointers, where each element points to one command-line argument string.

Example: What is a Pointer to a Pointer?

c
#include <stdio.h>
int main() {
	char *args[2] = {"prog", "arg1"};
	char **argv = args;
	printf("%s", argv[1]);
	return 0;
}

Declaring and Initializing

The declaration mirrors the double-pointer syntax you'd use for any type: int **pptr for pointers to int pointers, char **names for arrays of string pointers, and so on -- the type before the asterisks must match what's ultimately being pointed to.

Example: Declaring and Initializing

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

Dereferencing Once

This gives you an intermediate address in the chain -- if pptr points to ptr, then *pptr gives you ptr's value, which is itself an address (the one ptr points to), not yet the final data.

Example: Dereferencing Once

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

Dereferencing Twice

This is the operation that finally reaches the actual stored data at the bottom of the indirection chain, skipping past both layers of pointer addresses to get to the real value.

Example: Dereferencing Twice

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

Modifying Pointers in Functions

This pattern is common in functions that allocate memory and need to hand the new address back to the caller through a parameter, since a single pointer parameter would only let you modify a copy of the caller's pointer, not the original.

Example: Modifying Pointers in Functions

c
#include <stdio.h>
void allocate(int **out) {
	static int value = 10;
	*out = &value;
}
int main() {
	int *ptr = NULL;
	allocate(&ptr);
	printf("%d", *ptr);
	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.