As we know by now that a pointer stores the address of the pointed variable. But it is not the only use, pointer also stores the address of another pointer forming a chain like structure.
When we defined the pointer to a pointer, it means the first pointer contains the address of the second pointer and the second pointer contains the address of an actual variable.
We can declare the pointer to pointer variable by simply adding an additional asterisk * before the pointer name. example:
1 | int **pointer_name; |
C Program for Pointer to Pointer
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | #include <stdio.h> int main() { int x = 50; //pointer declaration int *ptr1; int **ptr2; //assigning address to pointer ptr1 = &x; ptr2 = &ptr1; //Printing the address of each variable printf("Address of x: %u\n", &x); printf("Address of p1: %u\n", &ptr1); printf("Address of p2: %u\n\n", &ptr2); //Printing the value that pointer and variable stores printf("Value stored by x: %u\n", x); printf("Value stored by ptr2: %d\n", *ptr2); printf("\nValue that **p2 pointing to: %d\n", **ptr2); return 0; } |
Output:
1 2 3 4 5 6 7 8 | Address of x: 556073700 Address of p1: 556073704 Address of p2: 556073712 Value stored by x: 50 Value stored by ptr2: 556073700 Value that **p2 pointing to: 50 |