Pointer to Pointer in C++
Pointer to Pointer (Double Pointer) Program in C++.
1#include <iostream>2using namespace std;34int main() {5 int num = 10;6 int* ptr = # // Pointer to int7 int** ptrToPtr = &ptr; // Pointer to pointer89 cout << "Value of num: " << num << endl;10 cout << "Address of num: " << &num << endl;1112 cout << "\nValue of ptr (address of num): " << ptr << endl;13 cout << "Address of ptr: " << &ptr << endl;14 cout << "Value pointed by ptr: " << *ptr << endl;1516 cout << "\nValue of ptrToPtr (address of ptr): " << ptrToPtr << endl;17 cout << "Address of ptrToPtr: " << &ptrToPtr << endl;18 cout << "Value pointed by ptrToPtr: " << *ptrToPtr << endl;19 cout << "Value pointed by *ptrToPtr: " << **ptrToPtr << endl;2021 // Modify value using double pointer22 **ptrToPtr = 20;23 cout << "\nAfter modifying through double pointer:" << endl;24 cout << "Value of num: " << num << endl;2526 return 0;27}
Output
Value of num: 10 Address of num: 0x7fff5fbff6ac Value of ptr (address of num): 0x7fff5fbff6ac Address of ptr: 0x7fff5fbff6a0 Value pointed by ptr: 10 Value of ptrToPtr (address of ptr): 0x7fff5fbff6a0 Address of ptrToPtr: 0x7fff5fbff698 Value pointed by ptrToPtr: 0x7fff5fbff6ac Value pointed by *ptrToPtr: 10 After modifying through double pointer: Value of num: 20
What's going on
The program demonstrates pointer to pointer operations:
Double pointers enable advanced memory management and data structures.
Header File Used
This header provides:
1#include <iostream>
Understanding Pointer to Pointer
Double Pointer Concept
:
Memory Layout
:
num (value: 10)
↑
ptr (points to num)
↑
ptrToPtr (points to ptr)
Declaring Double Pointer
Syntax
:
dataType** pointerName;
Example
:
int num = 10;
int* ptr = # // Single pointer
int** ptrToPtr = &ptr; // Double pointer
How it works
:
Two-Level Dereferencing
Accessing Values
:
*ptrToPtr // Gets value of ptr (address of num)
**ptrToPtr // Gets value of num (10)
How it works
:
Modifying Through Double Pointer
Modifying Value
:
**ptrToPtr = 20; // Changes num to 20
How it works
:
When to Use Double Pointers
Best For
:
Example Scenarios
:
Dynamic 2D Arrays
Example
:
int** matrix = new int*[rows];
for (int i = 0; i < rows; i++) {
matrix[i] = new int[cols];
}
How it works
:
Modifying Pointer in Function
Problem
: Function needs to modify pointer value
Solution
: Pass pointer to pointer
void allocateMemory(int** ptr) {
*ptr = new int(42); // Modifies original pointer
}
int* myPtr;
allocateMemory(&myPtr); // Pass address of pointer
Important Considerations
Dereferencing Levels
:
Memory Management
:
Complexity
:
return 0;
This ends the program successfully.