C Pointer to Pointer
A pointer to pointer (double pointer) stores the address of another pointer. It is written with two stars, like int **pp.
How it looks
| Variable | Stores |
|---|---|
num | The value (for example 50) |
p | Address of num |
pp | Address of p |
Example
#include <stdio.h>
int main(void) {
int num = 50;
int *p = #
int **pp = &p;
printf("num = %d\n", num);
printf("*p = %d\n", *p);
printf("**pp = %d\n", **pp);
**pp = 99; // change num
printf("num = %d\n", num);
return 0;
}
Output:
Output of the above program is
num = 50
*p = 50
**pp = 50
num = 99
One star *pp gives the pointer p. Two stars **pp go one step more and give the value of num.
Where is it used?
- Changing a pointer inside a function (the function needs the address of the pointer).
- Array of strings, like
char **argvin command line arguments. - Dynamic 2D arrays.
Change a pointer in a function
#include <stdio.h>
void point(int **pp, int *target) {
*pp = target;
}
int main(void) {
int a = 1, b = 2;
int *p = &a;
point(&p, &b);
printf("%d\n", *p);
return 0;
}
Output:
Output of the above program is
2
Note:
More than two levels (***p) are possible, but they are very rare. If you need it, think if there is a simpler design.
Next: C Pointers and Arrays.
Congratulations! Chapter Finished. Learn more about the similar topics:
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |