Pointer to Pointer in C: Explanation and Example
pointer to pointer is a variable that stores the address of another pointer variable. It allows indirect access to the value pointed to by the first pointer, enabling multiple levels of referencing.How It Works
Imagine you have a mailbox (a variable) that holds a letter (a value). A pointer is like a note that tells you where the mailbox is located. Now, a pointer to pointer is like a note that tells you where to find the first note. This means you have two levels of indirection: you first find the note, then use it to find the mailbox.
In C, a pointer holds the memory address of a variable. A pointer to pointer holds the address of a pointer variable. This lets you change the pointer itself or access the original value indirectly. It is useful when you want to manage pointers dynamically or pass pointers by reference to functions.
Example
This example shows how a pointer to pointer works by accessing and modifying an integer value through two levels of pointers.
#include <stdio.h> int main() { int value = 10; int *ptr = &value; // pointer to int int **ptr_to_ptr = &ptr; // pointer to pointer to int printf("Value: %d\n", value); printf("Value via ptr: %d\n", *ptr); printf("Value via ptr_to_ptr: %d\n", **ptr_to_ptr); // Change value using pointer to pointer **ptr_to_ptr = 20; printf("New value after change: %d\n", value); return 0; }
When to Use
Pointer to pointer is useful when you need to modify a pointer variable inside a function, such as dynamically allocating memory or changing where a pointer points. It is also common in handling arrays of strings or multi-dimensional arrays, where you have pointers to pointers to represent complex data structures.
For example, when you want a function to update a pointer to a new memory location, you pass a pointer to that pointer. This allows the function to change the original pointer's address, not just the data it points to.
Key Points
- A pointer to pointer stores the address of a pointer variable.
- It provides multiple levels of indirection to access or modify data.
- Commonly used for dynamic memory management and complex data structures.
- Allows functions to modify pointer variables by passing their addresses.