In C Language, a pointer to a pointer (or a double pointer) is a pointer variable that holds the address of another pointer variable.
Pointers to pointers are commonly used in scenarios where you need to dynamically allocate memory, manipulate arrays of strings, implement data structures like linked lists or trees, or for passing pointers by reference to functions.
Here's a example to illustrate the concept of pointers to pointers:
#include <stdio.h> #include <stdlib.h> int main() { int *ptr1; // Pointer to an integer int **ptr2; // Pointer to a pointer to an integer // Allocate memory for an integer ptr1 = (int *)malloc(sizeof(int)); printf("Allocate Memory location: %x and Assign Value: %d\n", ptr1, *ptr1); if (ptr1 == NULL) { printf("Memory allocation failed.\n"); return 1; } // Assign a value *ptr1 = 11; // Assign the address of ptr1 to ptr2 ptr2 = &ptr1; // Access the value using double indirection printf("Value of num using double indirection: %d\n", **ptr2); // Output: 11 // Free memory free(ptr1); return 0; }
Allocate Memory location: 4282a0 and Assign Value 0 Value of num using double indirection: 11
#include <stdio.h> #include <stdlib.h> void allocate_memory(int **ptr1, int **ptr2) { *ptr1 = (int *)malloc(sizeof(int)); *ptr2 = (int *)malloc(sizeof(int)); if (*ptr1 == NULL || *ptr2 == NULL) { printf("Memory allocation failed.\n"); exit(1); } **ptr1 = 11; **ptr2 = 22; } int main() { int *ptr1, *ptr2; // Call function to allocate memory and assign values allocate_memory(&ptr1, &ptr2); // Access the values printf("Value of ptr1: %d\n", *ptr1); // Output: 11 printf("Value of ptr2: %d\n", *ptr2); // Output: 22 // Free memory free(ptr1); free(ptr2); return 0; }
"ptr1" is a pointer to an integer.
"ptr2" is a pointer to a pointer to an integer.
Memory allocation functions like "malloc()" return void pointers "void *", so typecasting is necessary.
The function "allocate_memory()" takes two double pointers and allocates memory for two integers. It assigns values to these integers using double indirection.
"main()" function calls "allocate_memory()" by passing the addresses of "ptr1" and "ptr2".
After the memory is allocated and values are assigned, "main()" accesses these values through a single indirection.
Value of ptr1: 11 Value of ptr2: 22