A double pointer, also known as a pointer to a pointer, is a special type of pointer that holds the address of another pointer. In the C programming language, you can declare a double pointer using the **
notation.
Here’s an example to help illustrate the concept:
#include <stdio.h> int main() { int number = 42; int *ptr = &number; // Pointer to an integer int **doublePtr = &ptr; // Double pointer (pointer to a pointer) printf("Value of number: %d\n", number); printf("Value of ptr: %d\n", *ptr); printf("Value of doublePtr: %d\n", **doublePtr); return 0; }
In this example, we have an integer variable number
with the value 42
. We then declare a pointer ptr
that points to the address of number
. Finally, we declare a double pointer doublePtr
that points to the address of ptr
.
To access the value stored in number
, we can use number
directly or dereference ptr
using the *
operator (*ptr
). Similarly, to access the value of number
using the double pointer, we need to perform two levels of dereferencing (**doublePtr
).
Keep in mind that double pointers can be useful in certain situations, such as when working with dynamic memory allocation or when passing pointers to functions that need to modify the original pointer. However, they can make code more complex and harder to read, so they should be used judiciously.
C double pointer example:
Certainly! Here’s an example that demonstrates the use of a double pointer in C:
#include <stdio.h> void increment(int **ptr) { (**ptr)++; } int main() { int number = 42; int *ptr = &number; // Pointer to an integer int **doublePtr = &ptr; // Double pointer (pointer to a pointer) printf("Before increment: %d\n", **doublePtr); increment(&ptr); printf("After increment: %d\n", **doublePtr); return 0; }
In this example, we have a function called increment
that takes a double pointer as an argument. The increment
function increments the value stored at the address pointed to by the double pointer.
In the main
function, we have an integer variable number
with the initial value of 42
. We declare a pointer ptr
that points to the address of number
, and a double pointer doublePtr
that points to the address of ptr
.
We then pass the address of ptr
to the increment
function, which in turn increments the value stored at that address using two levels of dereferencing (**ptr
).
Finally, we print the value of number
before and after the increment operation to see the effect of the double pointer.
Output:
Before increment: 42 After increment: 43
As you can see, by using the double pointer and passing the address of the pointer to the function, we were able to modify the original value of number
.