Pointer to Pointer in C
A pointer to a pointer in C, often referred to as a "double pointer," is a pointer that stores the memory address of another pointer. It is a fundamental concept in C and is commonly used in scenarios where you need to manage dynamic memory allocation, function parameters, or multiple levels of indirection.
#include <stdio.h>
int main() {
int num = 42;
int* ptr = #
int** ptrToPtr = &ptr;
// Access the value using a pointer to a pointer
printf("Value of num: %d\n", **ptrToPtr);
// Modify the value indirectly through the pointer to a pointer
**ptrToPtr = 100;
// Verify the updated value
printf("Updated value of num: %d\n", num);
return 0;
}
Output:
Value of num: 42
Updated value of num: 100
In this example:
- We declare an integer variable
num
and assign it the value 42
.
- We declare a pointer
ptr
and assign it the address of num
.
- We declare a pointer to a pointer
ptrToPtr
and assign it the address of ptr
. ptrToPtr
now points to ptr
, which in turn points to num
.
- We access the value of
num
using the pointer to a pointer **ptrToPtr
, which allows us to indirectly access the value stored in num
.
- We modify the value of
num
indirectly through the pointer to a pointer. Changing **ptrToPtr
updates the value of num
.
- Finally, we verify that the value of
num
has been updated to 100
.
Pointer to pointer is a powerful concept in C, especially when working with dynamic memory allocation or when passing pointers as function arguments that need to be modified within the function. It enables multiple levels of indirection and is essential for working with complex data structures and managing memory efficiently.