A pointer to a pointer (or a double pointer) is a variable that stores the memory address of another pointer variable. This concept allows for multi-level indirection, which is essential for advanced memory management and array handling.
1. Declaration and Indirection Level
A double pointer is declared using two asterisks (**).
Syntax: dataType **pointerToPointerName;
int **pp_num; // Pointer to a pointer to an integer
char **pp_str; // Pointer to a pointer to a character (common for array of strings)
The number of asterisks indicates the level of indirection:
int num;$\rightarrow$ Valueint *p_num;$\rightarrow$ Level 1 Indirection (holds address ofnum)int **pp_num;$\rightarrow$ Level 2 Indirection (holds address ofp_num)
2. Using Pointers to Pointers
You need to use the dereference operator (*) multiple times to access the final value.
Example Workflow
int x = 100; // Original integer value
int *p = &x; // Pointer 'p' holds the address of 'x'
int **pp = &p; // Pointer 'pp' holds the address of 'p'
printf("Value of x: %d\n", x);
// 1. Access the value of p (which is the address of x)
printf("Address of x (via *pp): %p\n", *pp);
// 2. Access the value of x (two dereferences)
printf("Value of x (via **pp): %d\n", **pp); // Output: 100
// 3. Change the value of x via the double pointer
**pp = 200;
printf("New value of x: %d\n", x); // Output: 200
3. Application: Arrays of Strings
The most common real-world application of a double pointer is representing an array of strings.
- A string is a
char *(a pointer to the first character). - An array of strings is an array of
char *pointers, which requires achar **.
Example: Array of Strings
// An array of pointers to character strings
char *planets[] = {
"Mercury",
"Venus",
"Earth",
"Mars"
};
// 'planets' is treated as a char ** (a pointer to the first string pointer)
char **pp_planets = planets;
// Accessing the second string (Venus) using the double pointer
// *pp_planets accesses the pointer to "Mercury"
// *(pp_planets + 1) accesses the pointer to "Venus"
// *(*(pp_planets + 1)) is the character 'V'
printf("First planet: %s\n", *pp_planets);
// Move the pointer to the next element and print the string
pp_planets++;
printf("Second planet: %s\n", *pp_planets);
4. Application: Dynamic 2D Arrays
Pointers to pointers are also used to create truly dynamic two-dimensional arrays where both the number of rows and the number of columns can be determined at runtime using malloc().
// char **grid = (char **)malloc(rows * sizeof(char *));
// This structure is created using double pointers.
