03. Double Pointers & Multi-Level Indirection

🔴 Difficulty: Advanced | Pointers to Pointers (**ptr), Dynamic 2D Arrays & Pointer Mutation

📖 Definition

A double pointer (pointer to a pointer) is a pointer variable declared with two asterisks (**ptr) that stores the memory address of another pointer variable. Dereferencing once (*pptr) yields the intermediate pointer address; dereferencing twice (**pptr) yields the target data value.

🎯 Why It Is Used

  • Mutating Pointer Parameters inside Functions: Allowing a function to modify a caller's pointer variable (e.g. allocating heap memory inside a helper function or modifying a linked list head pointer).
  • Dynamic 2D Heap Allocations: Allocating ragged 2D arrays via an array of row pointers (int **matrix).
  • Command Line Argument Vector: Handling command line string arrays (char **argv).

⚙️ How It Works: Multi-Level Indirection Chain

[ Variable: val = 50 ]  <---  [ Pointer: ptr = &val ]  <---  [ Double Pointer: pptr = &ptr ]
(Address: 0x1000)             (Address: 0x2000)               (Address: 0x3000)
                              (Stores: 0x1000)                (Stores: 0x2000)
  • pptr contains 0x2000
  • *pptr yields 0x1000 (the address stored in ptr)
  • **pptr yields 50 (the value stored in val)

📝 Syntax

int val = 50;
int *ptr = &val;     // Single pointer storing address of val
int **pptr = &ptr;   // Double pointer storing address of ptr

**pptr = 100; // Modifies 'val' to 100 through two levels of indirection!

🔀 Caller Pointer Mutation Function Pattern

Just as mutating an int in a caller requires passing an int *, mutating an int * pointer in a caller requires passing an int ** double pointer!

🌱 Beginner Example: Dereferencing Chain Breakdown

#include <stdio.h>

int main(void) {
    int x = 42;
    int *p = &x;
    int **pp = &p;

    printf("x value                : %d\n", x);
    printf("*p (via single ptr)    : %d\n", *p);
    printf("**pp (via double ptr)  : %d\n", **pp);

    printf("p address (RAM)        : %p\n", (void*)p);
    printf("*pp address stored     : %p\n", (void*)*pp);

    return 0;
}

🌼 Intermediate Example: Allocating Heap Buffer via Helper Function

#include <stdio.h>
#include <stdlib.h>

// Accepts double pointer to allocate heap buffer and assign to caller's pointer!
void allocate_buffer(int **out_ptr, size_t count) {
    if (out_ptr == NULL) return;

    *out_ptr = (int*)malloc(count * sizeof(int));
    if (*out_ptr != NULL) {
        for (size_t i = 0; i < count; i++) {
            (*out_ptr)[i] = (int)(i + 1) * 10;
        }
    }
}

int main(void) {
    int *my_array = NULL;
    allocate_buffer(&my_array, 5); // Pass address of pointer 'my_array'!

    if (my_array != NULL) {
        printf("Heap Buffer Allocated Successfully:\n");
        for (int i = 0; i < 5; i++) {
            printf("%d ", my_array[i]);
        }
        printf("\n");
        free(my_array);
    }
    return 0;
}

🌲 Advanced Example: Dynamic 2D Ragged Matrix Allocation

#include <stdio.h>
#include <stdlib.h>

int main(void) {
    size_t rows = 3;
    size_t cols = 4;

    // 1. Allocate array of row pointers (int*)
    int **matrix = (int**)malloc(rows * sizeof(int*));
    if (matrix == NULL) return 1;

    // 2. Allocate each individual row buffer
    for (size_t r = 0; r < rows; r++) {
        matrix[r] = (int*)malloc(cols * sizeof(int));
        for (size_t c = 0; c < cols; c++) {
            matrix[r][c] = (int)(r * 10 + c);
        }
    }

    // 3. Print 2D matrix
    printf("=== Dynamic 2D Matrix (Double Pointer) ===\n");
    for (size_t r = 0; r < rows; r++) {
        for (size_t c = 0; c < cols; c++) {
            printf("%2d ", matrix[r][c]);
        }
        printf("\n");
    }

    // 4. Clean up memory in REVERSE order!
    for (size_t r = 0; r < rows; r++) {
        free(matrix[r]); // Free each row first
    }
    free(matrix); // Free outer row pointer array
    return 0;
}

🔍 Line-by-Line Explanation

  • allocate_buffer(&my_array, 5);: Passes address of single pointer variable my_array.
  • *out_ptr = malloc(...);: Modifies caller's my_array variable to point to newly allocated heap memory.
  • int **matrix = malloc(rows * sizeof(int*));: Allocates a contiguous array of row pointers on the heap.
  • free(matrix[r]); free(matrix);: Demonstrates proper sequential deallocation to avoid memory leaks.

💻 Expected Terminal Output

x value                : 42
*p (via single ptr)    : 42
**pp (via double ptr)  : 42
p address (RAM)        : 0x7ffe4210a004
*pp address stored     : 0x7ffe4210a004
Heap Buffer Allocated Successfully:
10 20 30 40 50
=== Dynamic 2D Matrix (Double Pointer) ===
 0  1  2  3
10 11 12 13
20 21 22 23 

⚠️ Common Mistakes & Pitfalls

  • Passing Single Pointer instead of Double Pointer: Writing allocate_buffer(my_array, 5) passes a pointer copy by value, leaving caller's my_array as NULL and leaking heap memory.
  • Freeing Outer Pointer Before Rows: Calling free(matrix) before freeing row buffers free(matrix[r]) loses row addresses, creating unrecoverable heap memory leaks.

📌 Important Rules & Limitations

  • To modify a single pointer variable inside a function, pass its address as a double pointer (&ptr).
  • Always deallocate dynamic 2D double-pointer matrices in reverse allocation order (rows first, outer array last).

🌐 Multilingual Explanation: English

A double pointer (**ptr) holds the address of a single pointer. Use double pointers to allow functions to allocate/modify caller pointers and to manage dynamic 2D heap arrays.

🌐 Multilingual Explanation: Hindi (Roman Script)

Double pointer (**ptr) doosre pointer ka memory address store karta hai. Function ke andar kisi pointer variable ki value badalne ke liye double pointer ka upyog hota hai.

🌐 Multilingual Explanation: Marathi (Roman Script)

Double pointer (**ptr) dusrya pointer cha RAM address hold karto. Function madhun caller cha pointer change karnyasathi double pointer pass kartat.

❓ Practice Questions

  1. Why is a double pointer required when a helper function allocates dynamic heap memory for a caller's pointer?
  2. How many levels of dereferencing are needed to access the target integer from an int ***p triple pointer?
  3. In what order must memory be freed for an int **matrix dynamic 2D array?

🚀 Practical Coding Challenge

Write a C program named linked_list_node.c that defines a simple node structure and a function void push_head(Node **head_ref, int new_data) that allocates a new node and mutates the caller's head pointer using a double pointer.

🧭 Navigation & Breadcrumbs

← Previous: 02. Pointer Arithmetic | Module 10 Guide | Next: 04. Const & Void Pointers →