đ Pointers to Pointers in C
A pointer to pointer in C is a variable that stores the address of another pointer. This concept is essential when dealing with dynamic memory allocation, multi-level data structures, and passing pointers to functions.
đ What is a Pointer to a Pointer?
Let’s break it down:
int *p;
— a pointer to an integer.int **pp;
— a pointer to a pointer to an integer.
int x = 10;
int *p = &x;
int **pp = &p;
Here’s what each variable holds:
x
→ stores the value 10p
→ stores the address ofx
pp
→ stores the address ofp
đ§Ē Example: Accessing Data with Pointer to Pointer
#include <stdio.h>
int main() {
int x = 10;
int *p = &x;
int **pp = &p;
printf("x = %d\n", x);
printf("*p = %d\n", *p);
printf("**pp = %d\n", **pp);
return 0;
}
✔ Output:
x = 10 *p = 10 **pp = 10
đ Diagram Explanation
x = 10 ↑ p = &x ↑ pp = &p
Use: Each asterisk (*
) is one level of dereferencing.
đ Changing Values using Pointer to Pointer
#include <stdio.h>
void modify(int **ptr) {
**ptr = 50;
}
int main() {
int val = 10;
int *p = &val;
int **pp = &p;
modify(pp);
printf("val = %d\n", val); // Output: 50
return 0;
}
Explanation: The function modify()
receives a pointer to pointer and modifies the original variable.
đ Real Use Case: Dynamic Memory Allocation (2D Array)
#include <stdio.h>
#include <stdlib.h>
int main() {
int **matrix;
int rows = 2, cols = 3;
matrix = (int **)malloc(rows * sizeof(int *));
for (int i = 0; i < rows; i++) {
matrix[i] = (int *)malloc(cols * sizeof(int));
}
// Assign values
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
matrix[i][j] = i + j;
printf("%d ", matrix[i][j]);
}
printf("\n");
}
// Free memory
for (int i = 0; i < rows; i++) {
free(matrix[i]);
}
free(matrix);
return 0;
}
Explanation: matrix
is a pointer to a pointer used to create a dynamic 2D array.
đ§ Summary
int *p;
→ pointer to an intint **pp;
→ pointer to a pointer to an int**pp
gives access to the original value- Used in advanced cases like dynamic 2D arrays and pointer manipulation in functions
đ§Š Practice Problems
- Write a program to print the address of a variable using a pointer to pointer.
- Create a function that swaps two integers using a pointer to pointer.
- Write a program to allocate and display a 3x3 matrix dynamically using
int **
.
āĻোāύ āĻŽāύ্āϤāĻŦ্āϝ āύেāĻ:
āĻāĻāĻি āĻŽāύ্āϤāĻŦ্āϝ āĻĒোāϏ্āĻ āĻāϰুāύ