C Pointer to Pointer
In this page:
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?
#include <stdio.h>
int main() {
char *args[2] = {"prog", "arg1"};
char **argv = args;
printf("%s", argv[1]);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
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
#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
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
#include <stdio.h>
int main() {
int x = 5;
int *ptr = &x;
int **pptr = &ptr;
printf("%p", (void*)*pptr);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
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
#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
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
#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 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: