๐ง C Double Pointers (Pointer to Pointer)
A double pointer in C is a pointer to another pointer. In other words, it’s a variable that stores the address of another pointer. These are useful for dynamic memory allocation, passing multidimensional arrays, and modifying pointer values inside functions.
๐น What is a Double Pointer?
A regular pointer stores the address of a variable. A double pointer stores the address of a pointer!
int a = 5; int *p = &a; int **pp = &p;
Here,
aholds 5pholds the address ofappholds the address ofp
๐ Example: Accessing Values Using Double Pointer
This example shows how to use a double pointer to access and print the value of a variable.
#include <stdio.h>
int main() {
int x = 100;
int *ptr = &x;
int **dptr = &ptr;
printf("Value of x = %d\n", x);
printf("Value using *ptr = %d\n", *ptr);
printf("Value using **dptr = %d\n", **dptr);
return 0;
}
๐ก Explanation
*ptrgives the value ofx.**dptralso gives the value ofxby dereferencing twice.- You’re digging deeper into memory with each level of indirection.
๐ฏ When to Use Double Pointers
- Dynamic memory allocation with functions like
malloc(). - Functions that modify pointer arguments (like creating arrays dynamically).
- Working with 2D arrays.
๐ Challenge
Write a function that accepts a char** and modifies the value it points to. Print the modified string from main().
๐ Summary
int **dptrmeans “pointer to pointer to int”.- Use double pointers when you want to modify a pointer itself inside a function.
**dptrgives you access to the final value.