C Double Pointers

๐Ÿ”ง C Double Pointers (Pointer to Pointer)

A double pointer in C is a pointer to another pointer. In other words, it’s a variable that stores the address of another pointer. These are useful for dynamic memory allocation, passing multidimensional arrays, and modifying pointer values inside functions.

๐Ÿ”น What is a Double Pointer?

A regular pointer stores the address of a variable. A double pointer stores the address of a pointer!

int a = 5;
int *p = &a;
int **pp = &p;

Here,

  • a holds 5
  • p holds the address of a
  • pp holds the address of p

๐Ÿ“ Example: Accessing Values Using Double Pointer

This example shows how to use a double pointer to access and print the value of a variable.

#include <stdio.h>

int main() {
    int x = 100;

    int *ptr = &x;
    int **dptr = &ptr;

    printf("Value of x = %d\n", x);
    printf("Value using *ptr = %d\n", *ptr);
    printf("Value using **dptr = %d\n", **dptr);

    return 0;
}
  

Try It Now

๐Ÿ’ก Explanation

  • *ptr gives the value of x.
  • **dptr also gives the value of x by dereferencing twice.
  • You’re digging deeper into memory with each level of indirection.

๐ŸŽฏ When to Use Double Pointers

  • Dynamic memory allocation with functions like malloc().
  • Functions that modify pointer arguments (like creating arrays dynamically).
  • Working with 2D arrays.

๐Ÿš€ Challenge

Write a function that accepts a char** and modifies the value it points to. Print the modified string from main().

๐Ÿ“Œ Summary

  • int **dptr means “pointer to pointer to int”.
  • Use double pointers when you want to modify a pointer itself inside a function.
  • **dptr gives you access to the final value.