C Pointer to Pointer
Pointer to Pointer
You can also have a pointer that points to another pointer. This is called a pointer to pointer (or "double pointer").
It might sound confusing at first, but it's just one more level of indirection: a pointer that stores the address of another pointer.
Think of it like this: A normal pointer is like a note with an address on it. A pointer to pointer is like another note telling you where that first note is kept.
Note: Pointer to pointer is not something you need to use often as a beginner. However, you might see it in more advanced programs, so it's good to understand what it means and how it works.
Let's look at a simple example to understand how this works:
Example
int main() {
int myNum = 10; // normal variable
int *ptr = &myNum; // pointer to int
int **pptr = &ptr; // pointer to pointer
printf("myNum = %d\n", myNum);
printf("*ptr = %d\n", *ptr);
printf("**pptr = %d\n", **pptr);
return 0;
}
Result:
myNum = 10
*ptr = 10
**pptr = 10
Here's what happens step by step:
myNumholds the value10.ptrholds the address ofmyNum.pptrholds the address ofptr.*ptrgives the value ofmyNum.**pptralso gives the value ofmyNum, by going through both pointers.
So:
*ptr= value ofmyNum**pptr= value ofmyNumthrough both levels
Changing Values Through a Pointer to Pointer
Since **pptr accesses the original variable,
you can use it to change the value of the variable too:
Example
int main() {
int myNum = 5;
int *ptr = &myNum;
int **pptr = &ptr;
**pptr = 20; // changes myNum
printf("myNum = %d\n", myNum); // prints 20
return 0;
}
Summary
- A pointer to pointer stores the address of another pointer.
*ptrgives the value of a variable.**pptrgives the same value by following two levels of indirection.- They can be useful when passing pointers to functions or working with complex data structures.