Pointer to Pointer in C
A pointer to pointer is a pointer variable that stores the address of another pointer. In other words, it is a pointer that points to another pointer that points to some data.
Definition
A pointer to pointer (or multi-level pointer) in C is used when you need to store the address of another pointer. This is typically used in advanced data structures or when working with dynamic memory allocation where you might need to manipulate the address of the pointer itself.
Syntax:
data_type **pointer_name;
How Pointer to Pointer Works
Consider a simple scenario where you have a pointer pointing to a variable, and you want to have a pointer that stores the address of this first pointer. This is where a pointer to pointer comes in.
Example 1: Pointer to Pointer
In this example, we declare an integer variable, a pointer to that variable, and a pointer to pointer that holds the address of the pointer.
Example:
{%raw%}
#include <stdio.h>
int main()
{
int num = 10;
int *ptr = # // Pointer to num
int **ptr2 = &ptr; // Pointer to pointer (ptr2 stores address of ptr)
printf("Value of num: %d\n", num);
printf("Address of num: %p\n", &num);
printf("Value of ptr (Address of num): %p\n", ptr);
printf("Value of ptr2 (Address of ptr): %p\n", ptr2);
printf("Value pointed to by ptr2 (Value of num): %d\n", **ptr2);
return 0;
}
{%endraw%}
Output
Address of num: 0x7ffee68d595c
Value of ptr (Address of num): 0x7ffee68d595c
Value of ptr2 (Address of ptr): 0x7ffee68d5950
Value pointed to by ptr2 (Value of num): 10
Pointer to Pointer with Arrays
Pointer to pointer can also be used when working with arrays, particularly multi-dimensional arrays. For example, when you want to use pointers to point to rows of a 2D array.
Example 2: Pointer to Pointer with Arrays
In this example, we use a pointer to pointer to access elements of a 2D array.
Example:
{%raw%}
#include <stdio.h>
int main()
{
int arr[2][2] = {{1, 2}, {3, 4}};
int *ptr1 = arr[0]; // Pointer to the first row
int **ptr2 = &ptr1; // Pointer to pointer
printf("Value of arr[0][0]: %d\n", **ptr2);
ptr1++; // Move to the next element of the first row
printf("Value of arr[0][1]: %d\n", **ptr2);
return 0;
}
Output
Value of arr[0][1]: 2
Key Points
- A pointer to pointer stores the address of another pointer, enabling multi-level indirection.
- Pointer to pointer is often used in cases involving dynamic memory allocation or when manipulating multi-dimensional arrays.
- Pointer arithmetic can be used with pointer to pointer to traverse arrays or dynamically allocated memory.
- To dereference a pointer to pointer, you use the dereference operator twice, once for each level of indirection.