C Pointer to Pointer
Syntax
The syntax for declaring a pointer to a pointer in C is as follows:
data_type** var_name;
Example
#include <stdio.h>
int main() {
int x = 10;
int* ptr1 = &x;
int** ptr2 = &ptr1;
printf("The value of x is %d\n", **ptr2);
printf("The address of x is %p\n", *ptr2);
printf("The value of ptr1 is %p\n", *ptr2);
printf("The address of ptr1 is %p\n", &ptr1);
printf("The value of ptr2 is %p\n", ptr2);
return 0;
}
Output
The output of the above code will be:
The value of x is 10
The address of x is 0x7fff5fbff8d4
The value of ptr1 is 0x7fff5fbff8d4
The address of ptr1 is 0x7fff5fbff8d8
The value of ptr2 is 0x7fff5fbff8d8
Explanation
A pointer to pointer, or double pointer, is a variable that stores the address of another pointer. It is used to access a pointer variable indirectly. The syntax for declaring a pointer to pointer is data_type** var_name.
In the example above, we declare an integer variable 'x' and create two pointers to it. The first pointer 'ptr1' stores the address of the 'x' variable, while the second pointer 'ptr2' stores the address of the 'ptr1' pointer.
We then print the values and addresses of the variables and pointers using printf statements. The ** operator is used to dereference the pointers and access the values stored in the variables.
Use
Pointers to pointers can be used for multiple levels of indirection. They can be used to implement complex algorithms, data structures, and dynamic memory allocation. They are also used in many operating system and network programming concepts.
Important Points
- A pointer to pointer is a variable that stores the address of another pointer.
- The syntax for declaring a pointer to pointer is data_type** var_name.
- The ** operator is used to access the value pointed to by a pointer to pointer.
- Pointers to pointers are used for multiple levels of indirection, and are commonly used in operating system and network programming.
Summary
A pointer to pointer is a variable that stores the address of another pointer, allowing for multiple levels of indirection in C programming. They are commonly used in complex algorithms, data structures, and dynamic memory allocation. Understanding the syntax and use cases for pointers to pointers is crucial for intermediate and advanced level C programming.