In C programming, a pointer to pointer, also known as a double pointer, is a powerful concept that allows you to store the address of another pointer variable. This advanced feature enables multi-level indirection and is particularly useful when working with complex data structures or dynamic memory allocation.
A pointer to pointer is declared using two asterisks (**) before the variable name. It can store the address of a pointer variable, which in turn stores the address of another variable or memory location.
int **ptr_to_ptr;
This declaration creates a pointer that can store the address of another pointer to an integer.
Here's a simple example demonstrating the use of a pointer to pointer:
int main() {
int x = 10;
int *ptr = &x;
int **ptr_to_ptr = &ptr;
printf("Value of x: %d\n", **ptr_to_ptr);
printf("Address of ptr: %p\n", (void*)ptr_to_ptr);
printf("Value of ptr: %p\n", (void*)*ptr_to_ptr);
return 0;
}
In this example, ptr_to_ptr
stores the address of ptr
, which in turn stores the address of x
.
One of the most common applications of pointers to pointers is dynamic allocation of 2D arrays:
int rows = 3, cols = 4;
int **array = (int **)malloc(rows * sizeof(int *));
for (int i = 0; i < rows; i++) {
array[i] = (int *)malloc(cols * sizeof(int));
}
// Use the array
array[1][2] = 42;
// Don't forget to free the memory when done
for (int i = 0; i < rows; i++) {
free(array[i]);
}
free(array);
This technique allows for flexible creation of 2D arrays with varying column sizes if needed.
To deepen your understanding of pointers in C, explore these related topics:
Mastering pointers to pointers in C opens up new possibilities for efficient memory management and complex data structure implementations. Practice regularly to become proficient in this advanced programming technique.