Understanding Double Pointers in C

Oct 28, 2024

C - Pointer to Pointer (Double Pointer)

Definition

  • A pointer to a pointer in C is used to store the address of another pointer.
  • The first pointer stores the address of a variable.
  • The second pointer stores the address of the first pointer, hence called double pointers.
  • Useful for changing values of normal pointers or creating variable-sized 2-D arrays.
  • Occupies the same memory space as a normal pointer.

Declaration

  • Syntax for declaring a pointer to a pointer:
    data_type_of_pointer **pointer_name = &normal_pointer_variable;
    
  • Example:
    int val = 5;
    int *ptr = &val; // storing address of val in pointer ptr
    int **d_ptr = &ptr; // pointer to a pointer declared
    

Example

#include<stdio.h>

int main() {
  int var = 789;
  int *ptr2;
  int **ptr1;
  ptr2 = &var;
  ptr1 = &ptr2;
  printf("Value of var = %d\n", var);
  printf("Value of var using single pointer = %d\n", *ptr2);
  printf("Value of var using double pointer = %d\n", **ptr1);
  return 0;
}

Output:

  • Value of var = 789
  • Value of var using single pointer = 789
  • Value of var using double pointer = 789

How Double Pointer Works

  • Double pointers are declared similarly to single pointers with an extra *.
  • They store the address of another pointer.
  • To manipulate or dereference, use the * operator the number of times matching the level.

Size of Pointer to Pointer

  • A double pointer's size is equal to a normal pointer's size.
  • Depends on machine architecture (usually 8 bytes for 64-bit and 4 bytes for 32-bit systems).

Example

#include<stdio.h>

int main() {
  int a = 5;
  int *ptr = &a;
  int **d_ptr = &ptr;
  printf("Size of normal Pointer: %d \n", sizeof(ptr));
  printf("Size of Double Pointer: %d \n", sizeof(d_ptr));
  return 0;
}

Output:

  • Size of normal Pointer: 8
  • Size of Double Pointer: 8

Applications

  • Dynamic memory allocation for multidimensional arrays.
  • Storing multilevel data, such as text document structures.
  • Manipulating node addresses in data structures directly.
  • Function arguments to manipulate local pointer addresses.

Multilevel Pointers

  • Double pointers are part of multilevel pointer support in C.
  • You can use triple pointers (pointer to a pointer to a pointer) and beyond.
  • Syntax for a triple pointer: pointer_type ***pointer_name;
  • Higher level pointers make programs complex and error-prone but are supported.

Note: Functions related to double pointers include Function Pointer in C.