Single Pointer and Double Pointer in C

Pointers are variables that store the memory address of another variable. They are widely used in C programming for dynamic memory allocation, function arguments, and efficient array handling.

We will discuss single pointers and double pointers, their purpose, and examples.

1. Single Pointer

A single pointer stores the address of a variable. It allows indirect access to the value of the variable using the dereference operator (*).

int x = 10;
int *p = &x; // p stores address of x
printf("Value of x = %d", *p); // Access value via pointer

Explanation:

• '&' operator gives the address of a variable.

• '*' operator dereferences the pointer to access the actual value.

C
Single pointer example
#include <stdio.h>

int main() {
    int x = 50;
    int *ptr; // single pointer

    ptr = &x; // store address of x

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

    return 0;
}

2. Double Pointer

A double pointer is a pointer that stores the address of another pointer. It is also called a pointer to pointer.

int x = 10;
int *p = &x;
int **q = &p;
printf("Value of x = %d", **q);

Explanation:

• '*' operator at first level dereferences the pointer to pointer and gives the address stored in the single pointer.

• '**' operator dereferences twice to access the actual value of the variable.

C
Double pointer example
#include <stdio.h>

int main() {
    int x = 100;
    int *ptr;       // single pointer
    int **dptr;     // double pointer

    ptr = &x;
    dptr = &ptr;

    printf("Address of x = %p\n", ptr);
    printf("Value of x using single pointer = %d\n", *ptr);
    printf("Value of x using double pointer = %d\n", **dptr);

    return 0;
}

3. Difference Between Single and Double Pointer

Single Pointer:
- Stores address of a variable
- Access value using *ptr
- Example: int *ptr;

Double Pointer:
- Stores address of another pointer
- Access value using **dptr
- Example: int **dptr;

4. Applications

Single Pointer Applications:

• Dynamic memory allocation using malloc(), calloc(), realloc().

• Function arguments to modify values of variables.

• Traversing arrays.

Double Pointer Applications:

• Dynamic allocation of 2D arrays.

• Array of pointers or pointer-based data structures.

• Passing pointer to pointer to functions to modify pointer values.

Conclusion

Single pointers store addresses of variables, while double pointers store addresses of single pointers. Both are crucial in C programming for memory management, dynamic data structures, and advanced function usage.

Understanding these pointers is essential for writing efficient and flexible C programs.