Pointer to Pointer
Pointer to Pointer (Double Pointer) Program in C++
IntermediateTopic: Memory Management Programs
C++ Pointer to Pointer Program
This program helps you to learn the fundamental structure and syntax of C++ programming.
#include <iostream>
using namespace std;
int main() {
int num = 10;
int* ptr = # // Pointer to int
int** ptrToPtr = &ptr; // Pointer to pointer
cout << "Value of num: " << num << endl;
cout << "Address of num: " << &num << endl;
cout << "\nValue of ptr (address of num): " << ptr << endl;
cout << "Address of ptr: " << &ptr << endl;
cout << "Value pointed by ptr: " << *ptr << endl;
cout << "\nValue of ptrToPtr (address of ptr): " << ptrToPtr << endl;
cout << "Address of ptrToPtr: " << &ptrToPtr << endl;
cout << "Value pointed by ptrToPtr: " << *ptrToPtr << endl;
cout << "Value pointed by *ptrToPtr: " << **ptrToPtr << endl;
// Modify value using double pointer
**ptrToPtr = 20;
cout << "\nAfter modifying through double pointer:" << endl;
cout << "Value of num: " << num << endl;
return 0;
}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
Understanding Pointer to Pointer
A pointer to pointer (double pointer) stores the address of another pointer. It's declared with
. Double pointers are useful for: 1) Dynamic 2D arrays, 2) Modifying pointer values in functions, 3) Linked lists and trees, 4) Passing pointers by reference. They require two levels of dereferencing (
ptrToPtr).
Let us now understand every line and the components of the above program.
Note: To write and run C++ programs, you need to set up the local environment on your computer. Refer to the complete article Setting up C++ Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your C++ programs.