![]() |
VOOZH | about |
In C, double pointers are those pointers which stores the address of another pointer. The first pointer is used to store the address of the variable, and the second pointer is used to store the address of the first pointer. That is why they are also known as a pointer to pointer.
var: 10 *ptr1: 10 **ptr2: 10
Explanation: In this code, ptr1 is a pointer that stores the address of the integer variable var. ptr2 is a double pointer that stores the address of the pointer ptr1. **ptr2 dereferences ptr2 to get the value of ptr1 (which is the address of var) and then dereferences that address to get the value of var itself.
Size of a double pointer is same as size of any other pointer as it also stored address.
8 bytes 8 bytes
Note: The output of the above code also depends on the type of machine which is being used.
Double pointers are useful in creating a dynamically sized 2D array where every row can have different number of elements.
1 2 3 4 5 6
Explanation: A 2D array is an array where each element is essentially a 1D array. This can be implemented using double pointers. The double pointer points to the first element of the 2D array, and each pointer it references points to a dynamically allocated 1D array using malloc().
Geek Geeks Geekfor
Explanation: Array of strings are generally stored as array of pointer to strings. This can be passed using double pointers to function.
Following are the main uses of pointer to pointers in C:
Double Pointers are not the only multilevel pointers supported by the C language. What if we want to change the value of a double pointer? In this case, we can use a triple pointer, which will be a pointer to a pointer to a pointer i.e, int ***t_ptr.
Value of num: 10 Value using single pointer: 10 Value using double pointer: 10
Note: We can use any level pointer in C. There is no restriction about it but it makes the program very complex and vulnerable to errors.