C++ Pointer to Pointer

A pointer to pointer (also called double pointer) in C++ is a pointer that stores the address of another pointer. It allows multiple levels of indirection.

1. Declaration of Pointer to Pointer

A pointer to pointer is declared using two asterisks (**).

C++
Syntax example
data_type **pointer_to_pointer;

// Example
int **ptr;

2. Initialization

A pointer to pointer is initialized by assigning it the address of another pointer.

C++
Example: Pointer to pointer initialization
#include <iostream>
using namespace std;

int main() {
    int num = 10;
    int *ptr = &num;
    int **pptr = &ptr;

    cout << "Value of num: " << **pptr << endl;
    return 0;
}

3. Dereferencing Pointer to Pointer

Dereferencing a pointer to pointer is done using ** to access the original value.

C++
Example: Dereferencing double pointer
#include <iostream>
using namespace std;

int main() {
    int num = 50;
    int *ptr = &num;
    int **pptr = &ptr;

    cout << "Address of num: " << pptr << endl;
    cout << "Value of num through double pointer: " << **pptr << endl;
    return 0;
}

4. Common Uses

1. Dynamic memory allocation for multi-dimensional arrays. 2. Passing pointers to functions to modify original pointers. 3. Managing arrays of pointers.

5. Important Notes

1. Always initialize both pointer and pointer-to-pointer. 2. Dereference carefully to avoid undefined behavior. 3. Multiple levels of pointers can be used, but readability decreases.

Conclusion

Pointer to pointer (double pointer) allows indirect access to a variable via multiple levels of indirection. It is useful in advanced C++ programming, especially with dynamic memory and pointer manipulation.