Lesson 40: Pointer to Pointer (Double Pointers)
A double pointer (or pointer to a pointer) is a variable that stores the address of another pointer variable.
Declaration
A double pointer uses two asterisks (**).
c int x = 10; int *p = &x; // p stores address of x int **pp = &p; // pp stores address of p
Dereferencing Double Pointers
pp: Holds the address ofp.*pp: Dereferences once, resulting in the content ofp(which is the address ofx).**pp: Dereferences twice, resulting in the content ofx(which is the value 10).
c printf("Value of x via **pp: %d\n", **pp); // 10
// We can change x using the double pointer **pp = 20; printf("New value of x: %d\n", x); // 20
Applications of Double Pointers
1. Passing a Pointer by Reference
This allows a function to change the actual address held by a pointer variable in the calling function (e.g., initializing a structure pointer or performing a dynamic array resize).
2. Implementing 2D Dynamic Arrays
Dynamically creating a 2D matrix requires allocating an array of pointers, where each pointer points to a dynamically allocated row (array of data).
c // Allocation for 10 rows (pointers), each pointing to 20 columns (integers) int **dynamic_matrix = (int **) malloc(10 * sizeof(int *)); for (int i = 0; i < 10; i++) { dynamic_matrix[i] = (int *) malloc(20 * sizeof(int)); }