As we already know that, pointer is used to store address of another variable. However, we can also declare a pointer variable to store address of another pointer, yes it is possible in C. When a pointer holds the address of another pointer variable this is known as double pointer or pointer to pointer. Let's see the below diagram to understand it better way:
Pointer to pointer Or Double pointer | welcome2protec.com |
Here is the syntax for declaring a double pointer (or pointer to pointer):
/* pointer to a pointer which is pointing to an integer var */
int **p
Let's understand with a simple example given at below:
Example of double pointer:
Double pointer or pointer to pointer is a form of multiple indirection, or chain of pointers as you can see in the above diagram. Let's have a look at the below example based on above diagram.
#include <stdio.h>
int main(){
int var = 10; /*Actual variable declaration*/
int *p; /*Normal pointer declaration*/
int **q; /*Double pointer declaration*/
p = &var; //Assigning the address of var in pointer p
/*Assigning the address of pointer p in double pointer q */
q = &p;
/*Possible ways to find the value of var*/
printf("Value of var = %d\n", var);
printf("Value of var = %d\n", *&var);
printf("Value of var using pointer p = %d\n", *p);
printf("Value of var using pointer q = %d\n", **q);
/*Possible ways to find the address of var*/
printf("Address of var = %x\n", &var);
printf("Address of var uisng pointer p = %x\n", p);
printf("Address of var using pointer q = %x\n", *q);
/*Print the value of poiners p and q*/
printf("Value stored at pointer p = %x\n", p);
printf("Value stored at pointer q = %x\n", q );
/*Print the address of poiners p and q*/
printf("Address of pointer p = %x\n", &p);
printf("Address of pointer q = %x\n", &q );
return 0;
}
When the above code will compile and run following output will be produced
Value of var = 10
Value of var = 10
Value of var = 10
Value of var = 10
Address of var = 0xbffd8b3c4c
Address of var uisng pointer p = 0xbffd8b3c4c
Address of var uisng pointer q = 0xbffd8b3c4c
Value stored at pointer p = 0xbffd8b3c4c
Value stored at pointer q = 0xbffd8b3c50
Address of pointer p = 0xbffd8b3c50
Address of pointer q = 0xbffd8b3c49
--
More on this to be updated soon...
--
--
0 Comments:
Post a Comment
Please don't enter any spam link in the comment box.