Swiftorial Logo
Home
Swift Lessons
Tutorials
Learn More
Career
Resources

Pointers to Pointers in C

Introduction

In C programming, a pointer is a variable that stores the address of another variable. A pointer to a pointer is a form of multiple indirection or a chain of pointers. It is a pointer that points to another pointer, which in turn points to another data value. This concept is essential for understanding dynamic memory allocation, arrays, and more complex data structures.

Basic Concept

A pointer to a pointer is declared using two asterisks. For example, int **ptr is a pointer to a pointer to an integer.

int a = 10; 
int *p; 
int **pp; 

p = &a;  // p now points to a
pp = &p; // pp now points to p
                

How to Declare a Pointer to a Pointer

To declare a pointer to a pointer, you can use the following syntax:

data_type **pointer_name;
                

For example:

int **pptr;
                

Accessing the Value

To access the value of the variable using a pointer to a pointer, you need to dereference the pointer twice.

#include <stdio.h>

int main() {
    int var = 3000;
    int *ptr;
    int **pptr;

    ptr = &var;   // Pointer 'ptr' holds the address of 'var'
    pptr = &ptr;  // Pointer 'pptr' holds the address of 'ptr'

    printf("Value of var = %d\n", var );
    printf("Value available at *ptr = %d\n", *ptr );
    printf("Value available at **pptr = %d\n", **pptr);

    return 0;
}
                
Output:
Value of var = 3000
Value available at *ptr = 3000
Value available at **pptr = 3000
                

Use Cases

Pointers to pointers are widely used in dynamic memory allocation. They are also used in data structures such as linked lists, trees, and graph algorithms. Here is an example where we use a pointer to a pointer for dynamic memory allocation:

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

int main() {
    int i, j;
    int row = 3;
    int col = 4;

    // Dynamically allocate memory for a 2D array
    int **array = (int **)malloc(row * sizeof(int *));
    for (i = 0; i < row; i++) {
        array[i] = (int *)malloc(col * sizeof(int));
    }

    // Assign values to the 2D array
    for (i = 0; i < row; i++) {
        for (j = 0; j < col; j++) {
            array[i][j] = i + j;
        }
    }

    // Print the 2D array
    for (i = 0; i < row; i++) {
        for (j = 0; j < col; j++) {
            printf("%d ", array[i][j]);
        }
        printf("\n");
    }

    // Free the allocated memory
    for (i = 0; i < row; i++) {
        free(array[i]);
    }
    free(array);

    return 0;
}
                
Output:
0 1 2 3 
1 2 3 4 
2 3 4 5
                

Conclusion

Pointers to pointers are a powerful concept in C that allow for complex data structures and efficient memory management. Understanding how to declare, access, and use pointers to pointers will greatly enhance your ability to write advanced C programs.