Course contentsShow
← C
Lesson 470 of 1,2197. PointersFree lesson

Navigating memory blocks manually

Navigating memory blocks manually

What you'll learn: How to use addition and subtraction to move a pointer across a contiguous block of data.

The sidewalk analogy

Imagine a long sidewalk where each concrete slab is exactly one yard wide. If you are standing on the first slab and someone tells you to move "plus two," you don't move two inches; you move two whole slabs down.

In C, pointer arithmetic works exactly the same way. When you add 1 to a pointer, you aren't adding a single byte to the memory address. Instead, the computer looks at the type of data the pointer is pointing to and jumps forward by the size of one whole element. If it’s an integer (usually 4 bytes), adding 1 moves the address forward by 4 bytes.

Math that respects size

Because pointers "know" the size of their data type, we can navigate through arrays or allocated memory blocks without manually calculating byte offsets. We simply tell the pointer how many "steps" to take.

#include <stdio.h>

int main() {
    int numbers[] = {10, 20, 30, 40, 50};
    int *ptr = numbers; // Points to the first element (10)

    // Move the pointer two 'steps' forward
    ptr = ptr + 2; 
    
    // This will print 30, not 10 + 2
    printf("Current value: %d\n", *ptr);

    // Move one step back
    ptr--;
    
    // This will print 20
    printf("Previous value: %d\n", *ptr);

    return 0;
}

Why this matters

Pointer arithmetic is the engine behind how C handles arrays. When you write numbers[2], the compiler is actually performing pointer arithmetic under the hood: it takes the starting address and adds two "steps" of the integer size to find the value.

By using ptr++ or ptr + n, you are manually steering through memory. This is incredibly powerful for processing strings, parsing data packets, or iterating through large buffers of information efficiently. You aren't just looking at a single box in memory; you are navigating a map where the "step size" is automatically calibrated to the data you're working with.

Key takeaway

Adding to a pointer moves it forward by that many elements, not bytes, based on its data type.