Pointers Deep Dive
Pointers are C’s superpower. They enable direct memory manipulation, efficient data structures, and system-level programming. While they have a reputation for being difficult, they are just variables that store addresses.Pointers in C
At its core, a pointer is just a number—the address of a byte in memory.Why Does C Have Pointers?
The Fundamental Problem
Before learning pointer syntax, understand why they exist: The problem: How do you write efficient, low-level code? In high-level languages, you work with “values”:- Pass a 1MB struct to a function? Copy all 1MB
- Return a large array? Copy it back
- Modify a parameter? Can’t affect the original
- Pass a pointer (8 bytes) instead of copying 1MB
- Return a pointer instead of copying data
- Modify data through a pointer to affect the original
- Implement efficient data structures (linked lists, trees)
- Interface with hardware (memory-mapped I/O)
- Implement system calls (kernel needs to modify user memory)
- Build operating systems and drivers
Pointer Fundamentals
Memory Model
Pointer Types
Pointer Arithmetic
Pointer arithmetic is one of the most confusing yet powerful features of C. It allows you to navigate memory based on the type of data you are pointing to.What’s Allowed
Pointer Arithmetic Visualized
p + 1, the compiler doesn’t add 1 byte to the address. Instead, it adds sizeof(*p) bytes. This is why pointer arithmetic “just works” with arrays:
- Enables efficient array traversal
- Allows treating arrays as pointers
- Foundation for dynamic data structures
- Critical for understanding
sizeofand alignment
Arrays and Pointers
Array Decay
In C, arrays and pointers are closely related but NOT identical. The most important concept to grasp is “array decay”.Multi-dimensional Arrays
Pointers to Pointers
Array of Pointers vs Pointer to Array
Const Correctness
Void Pointers
Generic Container with void*
The Restrict Keyword
Function Pointers
Common Pitfalls
Dangling Pointers
Null Pointer Dereference
Wild Pointers
Exercises
1
Pointer Puzzle
Given
int a = 5, *p = &a, **pp = &p;, trace what each of these expressions evaluates to: *p, **pp, *pp, &p, &a, p[0].2
Custom memcpy
Implement your own
void *my_memcpy(void *dest, const void *src, size_t n) using only pointer operations.3
Reverse Array In-Place
Write
void reverse(int *arr, size_t n) using only pointer arithmetic (no array indexing []).4
Generic Sorting
Write a sorting function that accepts array, size, element size, and comparison function pointer, like
qsort.5
2D Dynamic Array
Implement a dynamically allocated 2D array with functions to create, access, and free it.
Next Up
Memory Layout & Segments
Understand how programs use memory