🔗 Understanding Pointer to Pointer in C

🔗 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 10
  • p → stores the address of x
  • pp → stores the address of p

đŸ§Ē 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 int
  • int **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

  1. Write a program to print the address of a variable using a pointer to pointer.
  2. Create a function that swaps two integers using a pointer to pointer.
  3. Write a program to allocate and display a 3x3 matrix dynamically using int **.
pointer to pointer in c, c double pointer tutorial, **pp in c, c pointer chain, double indirection in c, dynamic memory with pointer to pointer

āĻ•োāύ āĻŽāύ্āϤāĻŦ্āϝ āύেāχ:

āĻāĻ•āϟি āĻŽāύ্āϤāĻŦ্āϝ āĻĒোāϏ্āϟ āĻ•āϰুāύ