C Double Pointer (Pointer to Pointer)
Categories: C language
As we know that, a pointer is used to store the address of a variable in C. Pointer reduces the access time of a variable. However, In C, we can also define a pointer to store the address of another pointer. Such pointer is known as a double pointer (pointer to pointer). The first pointer is used to store the address of a variable whereas the second pointer is used to store the address of the first pointer. Let's understand it by the diagram given below.
The syntax of declaring a double pointer is given below.
int **p; // pointer to a pointer which is pointing to an integer.
Consider the following example.
#include<stdio.h>
void main ()
{
int a = 10;
int *p;
int **pp;
p = &a; // pointer p is pointing to the address of a
pp = &p; // pointer pp is a double pointer pointing to the address of pointer p
printf("address of a: %x\n",p); // Address of a will be printed
printf("address of p: %x\n",pp); // Address of p will be printed
printf("value stored at p: %d\n",*p); // value stoted at the address contained by p i.e. 10 will be printed
printf("value stored at pp: %d\n",**pp); // value stored at the address contained by the pointer stoyred at pp
}
Output
address of a: d26a8734
address of p: d26a8738
value stored at p: 10
value stored at pp: 10
In the above question, the pointer arithmetic is used with the double pointer. An array of 6 elements is defined which is pointed by an array of pointer p. The pointer array p is pointed by a double pointer pp. However, the above image gives you a brief idea about how the memory is being allocated to the array a and the pointer array p. The elements of p are the pointers that are pointing to every element of the array a. Since we know that the array name contains the base address of the array hence, it will work as a pointer and can the value can be traversed by using *(a), *(a+1), etc. As shown in the image, a[0] can be accessed in the following ways.
1. a[0]: it is the simplest way to access the first element of the array
2. *(a): since a store the address of the first element of the array, we can access its value by using indirection pointer on it.
3. *p[0]: if a[0] is to be accessed by using a pointer p to it, then we can use indirection operator (*) on the first element of the pointer array p, i.e., *p[0].
4. **(pp): as pp stores the base address of the pointer array, *pp will give the value of the first element of the pointer array that is the address of the first element of the integer array. **p will give the actual value of the first element of the integer array.