C++ Pointer to Pointer
In C++, a pointer to pointer is a type of pointer that stores the address of another pointer. This allows for multiple levels of indirection, which can be useful in situations like dynamic memory allocation, multi-dimensional arrays, or when working with complex data structures.
A pointer to pointer is declared using two asterisks (**
) and is often referred to as a “double pointer.”
Syntax
</>
Copy
data_type** pointer_name;
- data_type
- The type of data that the final pointer will point to.
- pointer_name
- The name of the pointer to pointer variable.
Examples
Example 1: Basic Pointer to Pointer
This example demonstrates how to declare, initialize, and access a pointer to pointer.
</>
Copy
#include <iostream>
using namespace std;
int main() {
int num = 42;
int* ptr = # // Pointer to an integer
int** ptr2 = &ptr; // Pointer to pointer
cout << "Value of num: " << num << endl;
cout << "Value of num using *ptr: " << *ptr << endl;
cout << "Value of num using **ptr2: " << **ptr2 << endl;
return 0;
}
Output:
Value of num: 42
Value of num using *ptr: 42
Value of num using **ptr2: 42
Explanation:
- The variable
num
is declared and initialized to42
. - The pointer
ptr
is assigned the address ofnum
using the address-of operator (&
). - The pointer to pointer
ptr2
is assigned the address ofptr
. *ptr
dereferences the first pointer, accessing the value ofnum
.**ptr2
dereferences the second pointer, which accessesnum
throughptr
.
Example 2: Modifying a Value Using Pointer to Pointer
This example demonstrates how a pointer to pointer can be used to modify the value of a variable.
</>
Copy
#include <iostream>
using namespace std;
void modifyValue(int** ptr2) {
**ptr2 = 100; // Modify the value pointed by the pointer
}
int main() {
int num = 42;
int* ptr = # // Pointer to an integer
int** ptr2 = &ptr; // Pointer to pointer
cout << "Before modification: " << num << endl;
modifyValue(ptr2); // Pass the pointer to pointer
cout << "After modification: " << num << endl;
return 0;
}
Output:
Before modification: 42
After modification: 100
Explanation:
- The variable
num
is declared and initialized to42
. - The pointer
ptr
is assigned the address ofnum
. - The pointer to pointer
ptr2
is assigned the address ofptr
. - The function
modifyValue
is called withptr2
as an argument. Inside the function,**ptr2
dereferences the pointer twice to access and modify the value ofnum
. - After the function call, the value of
num
is updated to100
.
Key Points to Remember about Pointer to Pointer
- A pointer to pointer stores the address of another pointer.
- It allows for multiple levels of indirection, enabling access to the value indirectly.
- To access the value, the pointer must be dereferenced multiple times (e.g.,
**ptr2
). - Pointers to pointers are commonly used in dynamic memory allocation, passing arrays to functions, and working with complex data structures.