How to Use Double Pointer in C: Syntax and Examples
In C, a
double pointer is a pointer that stores the address of another pointer. It is declared as type **ptr and is useful for modifying pointer values inside functions or managing dynamic arrays of pointers.Syntax
A double pointer is declared by adding two asterisks ** before the pointer name. For example, int **ptr means ptr points to a pointer that points to an int.
type: the data type the final pointer points to (e.g.,int).**ptr: double pointer variable.
You can use it to store the address of a pointer variable.
c
int **ptr;Example
This example shows how to use a double pointer to change the value of a pointer inside a function. The double pointer allows the function to modify the original pointer's address.
c
#include <stdio.h> void updatePointer(int **p) { static int value = 100; *p = &value; // Change the pointer to point to 'value' } int main() { int x = 10; int *ptr = &x; printf("Before: *ptr = %d\n", *ptr); // Prints 10 updatePointer(&ptr); // Pass address of ptr (double pointer) printf("After: *ptr = %d\n", *ptr); // Prints 100 return 0; }
Output
Before: *ptr = 10
After: *ptr = 100
Common Pitfalls
Common mistakes when using double pointers include:
- Not initializing the pointer before dereferencing it, causing undefined behavior.
- Confusing single and double pointers, leading to wrong memory access.
- Forgetting to pass the address of the pointer when calling a function that expects a double pointer.
Always ensure the pointer you point to is valid and properly allocated.
c
#include <stdio.h> void wrongUpdate(int *p) { static int value = 50; p = &value; // This changes local copy only, original pointer unchanged } void correctUpdate(int **p) { static int value = 50; *p = &value; // Changes original pointer } int main() { int x = 5; int *ptr = &x; wrongUpdate(ptr); printf("After wrongUpdate: *ptr = %d\n", *ptr); // Still 5 correctUpdate(&ptr); printf("After correctUpdate: *ptr = %d\n", *ptr); // Now 50 return 0; }
Output
After wrongUpdate: *ptr = 5
After correctUpdate: *ptr = 50
Quick Reference
Tips for using double pointers:
- Use
type **ptrto hold the address of a pointer. - Pass
&ptrto functions to modify the original pointer. - Double pointers are useful for dynamic 2D arrays and linked list manipulations.
- Always check pointers before dereferencing to avoid crashes.
Key Takeaways
A double pointer stores the address of another pointer and is declared as type **ptr.
Use double pointers to modify pointer variables inside functions by passing their address.
Always initialize pointers before dereferencing to avoid undefined behavior.
Double pointers are useful for dynamic arrays and complex data structures.
Pass the address of a pointer (using &) when a function expects a double pointer.