In C programming, a pointer to pointer (commonly referred to as a double pointer) is a pointer that stores the address of another pointer. This allows for multiple levels of indirection, which can be useful for dynamic memory allocation, passing pointers to functions, and working with multidimensional arrays.
Declaration
int **ptr;
Here:
ptr
is a double pointer.- It can store the address of a pointer to an integer.
Concept
- Pointer: A pointer holds the address of a variable.
int a = 10; int *p = &a; // 'p' stores the address of 'a'
- Pointer to Pointer: A pointer to a pointer holds the address of another pointer.
int **pp = &p; // 'pp' stores the address of 'p'
How It Works
- A single pointer provides one level of indirection:
*p = value
Here,
*p
accesses the value at the address stored inp
. - A double pointer provides two levels of indirection:
**pp = value
Here,
**pp
accesses the value at the address stored in the pointer thatpp
points to.
Example
#include <stdio.h>
int main() {
int a = 10;
int *p = &a; // Pointer to 'a'
int **pp = &p; // Pointer to pointer 'p'
printf("Value of a: %d\n", a); // 10
printf("Address of a: %p\n", &a); // Address of 'a'
printf("Value of p (address of a): %p\n", p); // Address of 'a'
printf("Value at p (value of a): %d\n", *p); // 10
printf("Address of p: %p\n", &p); // Address of 'p'
printf("Value of pp (address of p): %p\n", pp); // Address of 'p'
printf("Value at pp (value of p): %p\n", *pp); // Address of 'a'
printf("Value at *pp (value of a): %d\n", **pp); // 10
return 0;
}
Use Cases
- Dynamic Memory Allocation: Double pointers are used in dynamic allocation of 2D arrays using
malloc
:int rows = 3, cols = 4; int **array = malloc(rows * sizeof(int *)); for (int i = 0; i < rows; i++) { array[i] = malloc(cols * sizeof(int)); }
- Pointer Function Arguments: To modify a pointer in a function, a pointer to a pointer is passed:
void updatePointer(int **ptr) { static int b = 20; *ptr = &b; } int main() { int a = 10; int *p = &a; printf("Before: %d\n", *p); // 10 updatePointer(&p); printf("After: %d\n", *p); // 20 return 0; }
- Linked Lists: Double pointers are often used for handling pointers to nodes during insertion or deletion in a linked list.
Benefits
- Flexibility: Enables complex data structures like 2D arrays, linked lists, and trees.
- Control: Provides control over dynamic memory allocation and pointer manipulation.
- Efficiency: Useful for passing pointers to functions when changes need to be reflected outside the function.
Key Points
- A double pointer allows you to manipulate the value of a pointer.
- Syntax for dereferencing:
*ptr
: Accesses the value stored at the pointer.**ptr
: Accesses the value stored at the address pointed to by another pointer.
- Always ensure proper memory management to avoid segmentation faults or memory leaks.