A pointer is a variable that points to the address of a variable in memory. Often it happens that we need a pointer to point at the pointer itself (yeah it can come to that). Such a pointer is known as a double pointer.
The first pointer stores the address of the assigned variable. And the second pointer stores the address of the first pointer. That is why they are known as double-pointers.
The double pointers are specified by **
.
int **ptr; //declaration of double pointer
Actually, we can extend the notion to multiple pointers. C++ maintains the sleekness as the number of preceding asterisks can determine the type of pointer (single, double, triple, or so on).
In the figure below, we create a variable with the value, ptr_1
, is pointing to the variable so this pointer has the address of a variable. Then we declare another pointer, ptr_2
, which points to ptr_1
. So, ptr_2
stores the address of ptr_1
. This is how a double pointer works.
#include <iostream>using namespace std;int main() {int variable=14;// First Pointerint *ptr_1;ptr_1 = &variable; //storing the address of variable//Double Pointerint **ptr_2;ptr_2 = &ptr_1; //storing the address of ptr_1//printing out the values of variable,pointer and double pointercout << "Address of var [&var] :" << &variable << "\n";cout << "Value of var [var ] :" << variable << "\n\n";cout << "Address of Pointer [pt ] :" << ptr_1 << "\n";cout << "Variable value by Pointer [*pt ] :" << *ptr_1 << "\n\n";cout << "Address of Double Pointer [dp ] :" << ptr_2 << "\n";cout << "Value of Double Pointer [*dp ] :" << *ptr_2 << "\n";cout << "Variable value by Double Pointer[**dp] :" << **ptr_2 << "\n";return 0;}
We initialized a variable
by 14. The first pointer *ptr_1
points to the address of variable
. Then we declare the second pointer which is double-pointer **ptr_2
that points to the ptr_1
. Afterward, we print all the values of variable
, *ptr_1
, *ptr_2
.
Note: A double-pointer is use for declaration of the dynamic 2D array.
Free Resources