C Pointer to Pointer

C Tutorial

 Explore the concept of C Pointer to Pointer in this comprehensive guide. Understanding pointers is essential for effective programming in C, and pointers to pointers offer advanced techniques for managing memory and data structures. This article delves into the syntax, usage, and practical applications of C Pointer to Pointer, providing valuable insights for both novice and experienced developers. Enhance your coding skills by mastering this critical aspect of C programming.

1. What is a C Pointer to Pointer?

  • In C Pointer to Pointer points to a pointer variable, which in turn points to another variable.

  • It’s like two levels of indirection:

variable -> value
pointer -> address of variable
pointer-to-pointer -> address of pointer

Syntax:

data_type **ptr2;
  • data_type → type of variable being pointed to

  • ** → indicates double pointer


2. Example: Basic Pointer to Pointer

Output (example):

Value of num = 50
Address of num = 0x7ffee3b2c8ac
Value of ptr (address of num) = 0x7ffee3b2c8ac
Value pointed by ptr = 50
Address of ptr = 0x7ffee3b2c8b0
Value of pptr (address of ptr) = 0x7ffee3b2c8b0
Value pointed by pptr (value of ptr) = 0x7ffee3b2c8ac
Value pointed twice by pptr = 50

*pptr → value of ptr (address of num)
**pptr → value of num


3. Pointer to Pointer with Functions

  • Pointers to pointers are used for modifying pointers inside functions.

Output:

Before: *ptr = 50
After: *ptr = 100

Passing &ptr allows the function to modify the pointer itself, not just the value it points to.


4. Pointer to Pointer with Arrays of Pointers

Output:

Alice
Bob
Charlie

ptr is a pointer to the first string pointer.


5. Key Points About Pointer to Pointer

  1. Declared using data_type **ptr2;.

  2. *ptr2 gives the value of the first pointer.

  3. **ptr2 gives the value of the actual variable.

  4. Useful for:

    • Modifying pointers inside functions

    • Arrays of strings

    • Dynamic memory allocation (double pointers for 2D arrays)

You may also like...