C++ Pointers Pointers
Syntax
A Pointer Pointer in C++ is a pointer to another pointer or a double pointer. The syntax for declaring a pointer pointer is as follows:
datatype** var_name;
Example
Here's an example of a pointer pointing to another pointer:
int main() {
int a = 5;
int* ptr1 = &a;
int** ptr2 = &ptr1;
cout << "The value of a: " << a << endl;
cout << "The value of ptr1: " << *ptr1 << endl;
cout << "The value of ptr2: " << **ptr2 << endl;
return 0;
}
Output
The output of the above code will be:
The value of a: 5
The value of ptr1: 5
The value of ptr2: 5
Explanation
In the above code, we first declare an integer variable a
and initialize it to 5.
Then, we declare a pointer ptr1
and assign it the address of a
. This means that ptr1
is now pointing to a
.
Next, we declare a pointer pointer ptr2
and assign it the address of ptr1
. This means that ptr2
is now pointing to ptr1
.
We then print the value of a
, which is 5, by dereferencing a
using the *
operator on ptr1
.
Similarly, we print the value of ptr1
by dereferencing ptr1
using the *
operator on ptr2
.
Finally, we print the value of a
again by dereferencing a
twice using the **
operator on ptr2
.
Use
Pointer pointers are often used in advanced data structures such as trees and graphs.
They can also be used to create dynamic arrays of pointers.
Important Points
- A pointer pointer is a pointer to another pointer.
- The syntax for declaring a pointer pointer is
datatype** var_name;
. - We can access the value of a pointer pointer by using the
**
operator. - Pointer pointers are often used in advanced data structures.
Summary
In this tutorial, we learned about pointer pointers in C++. We saw how to declare a pointer pointer, how to access its value, and where it is commonly used. We also saw an example and the output of a program that uses a pointer pointer.