Back to C Systems Pro
Intermediate
30 min Read

Mastering Pointers

Learning Objectives

  • Pointer Arithmetic
  • Pointer to Pointers
  • Function Pointers

Mastering Pointers: Memory Addressing

Pointers are the soul of C. They allow for zero-copy data processing, efficient data structures, and direct hardware interaction.

Pointer Arithmetic: Beyond the Basics

A pointer is just a memory address, but the type of the pointer tells the compiler how much to jump when you increment it.

c code
int arr[5] = {10, 20, 30, 40, 50};
int *p = arr;

// p + 1 jumps 4 bytes (size of int)
printf("Value: %d\n", *(p + 1)); // 20

Function Pointers: Strategy Pattern in C

Industry-level C uses function pointers for callbacks, plugin systems, and implementing polymorphic behavior.

c code
typedef int (*calc_func)(int, int);

int add(int a, int b) { return a + b; }
int multiply(int a, int b) { return a * b; }

void execute(calc_func f, int x, int y) {
    printf("Result: %d\n", f(x, y));
}

int main() {
    execute(add, 5, 3);      // 8
    execute(multiply, 5, 3); // 15
    return 0;
}

Pointer to Pointers (Double Pointers)

Commonly used when a function needs to modify a pointer passed to it (e.g., allocating memory inside a function).

c code
void allocate_memory(int **ptr) {
    *ptr = (int *)malloc(sizeof(int) * 10);
}

The "Dangling Pointer" Trap

Always nullify your pointers after free()'ing them. Accessing a freed pointer is a critical security vulnerability (Use-After-Free).

Confused about this chapter?

Ask our DevVault AI Assistant for instant clarification!

Ask DevVault AI