Pointer to Pointer in C Programming
C allows the use of pointers that points to other pointers. For making pointer to point another pointer we need to add extra * to a pointer variable.
Pointer to Pointer Examples
-
In this declaration p is normal variable, ptr is pointer to integer and pptr is pointer to pointer.int p=10, *ptr, **pptr;
-
In this declaration f is normal variable, fp is pointer to float, fpt is pointer to pointer and fptr is pointer to pointer to pointer.float f=50.5, *fp, **fpt, ***fptr;
-
Here e, f, g and h are all pointer to pointer.char c, *d, **e, ***f, ****g, *****h;
Theoretically there is no limit on how many stars that can be added before a pointer variable but there will be some limit and this limit comes from how the compiler is designed and what system you are using!
So, how does pointer to pointer work? Huh! Consider following programming examples, we will go line by line.
Pointer to Pointer Example
C Source Code
#include<stdio.h>
int main()
{
int p=10, *q, **r, ***s;
/* Referencing */
q = &p;
r = &q;
s = &r;
/* Some Results */
printf("\nValue of p = %d", p);
printf("\nValue of p using pointer q = %d", *q);
printf("\nValue of p using pointer r = %d", **r);
printf("\nValue of p using pointer s = %d", ***s);
return 0;
}
Output
Value of p = 10 Value of p using pointer q = 10 Value of p using pointer r = 10 Value of p using pointer s = 10
Explanation: Pointer to Pointer Example
In this program is p is normal variable, q is pointer to integer which means it can point to some integer variable. When statement
Remember dereferencing? After referencing, *q is *&p and to remember if & comes after * i.e. *& (not &*) then you can cancel that out :). So after canceling *& from *&p we get p right?
Let’s apply same logic for other statement!! Here r is pointer to pointer so it can store address of any pointer variable of type integer. And this is exactly what we are doing using r = &q; After this assignment, pointer to pointer variable r is storing address of another pointer variable q. So **r is *(*&)q=>*q=>(*&)p=>p :)
Similarly, s = &r; ***s=>**(*&)r=>**r=> *(*&)q=>*q=>(*&)p=>p :) So form all statements we get value of p which is equal to 10.
Hope that sounds good :P
q = &p;
is executed then pointer q is storing address of p so value of p can be dereferenced using q. Remember dereferencing? After referencing, *q is *&p and to remember if & comes after * i.e. *& (not &*) then you can cancel that out :). So after canceling *& from *&p we get p right?
Let’s apply same logic for other statement!! Here r is pointer to pointer so it can store address of any pointer variable of type integer. And this is exactly what we are doing using r = &q; After this assignment, pointer to pointer variable r is storing address of another pointer variable q. So **r is *(*&)q=>*q=>(*&)p=>p :)
Similarly, s = &r; ***s=>**(*&)r=>**r=> *(*&)q=>*q=>(*&)p=>p :) So form all statements we get value of p which is equal to 10.
Hope that sounds good :P