C Double Pointers
In this page:
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?
#include <stdio.h>
int main() {
int x = 5;
int *ptr = &x;
int **pptr = &ptr;
printf("%d", **pptr);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
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
#include <stdio.h>
int main() {
int x = 5;
int *ptr = &x;
int **pptr = &ptr;
printf("%d", **pptr);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
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
#include <stdio.h>
int main() {
int x = 5;
int *ptr = &x;
int **pptr = &ptr;
printf("%d", *ptr);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
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 ()
#include <stdio.h>
int main() {
int x = 5;
int *ptr = &x;
int **pptr = &ptr;
printf("%d", **pptr);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
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
#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 try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 9 topics to unlock
0/9 topics done
Complete these topics first: