C/C++ Arena

Pointer arithmetic

How adding to a pointer moves by whole elements, how p[i] relates to *(p + i), and where pointer arithmetic becomes undefined.

Adding 1 to a pointer moves it to the next element, not the next byte: for an int * that's usually 4 bytes along. That's why p[i] means exactly *(p + i).

Subtracting two pointers into the same array gives how many elements apart they are. You may point one past the last element (useful as an end marker), but reading it, or going further, is undefined behavior.

Example

#include <stdio.h>

int main(void) {
    int a[] = {5, 10, 15, 20};
    int *p = a;
    int *end = a + 4;
    printf("%d %d %d\n", *(p + 2), p[3], (int)(end - p));
    return 0;
}

Output:

15 20 4

Watch it run: Pointer arithmetic walks an array

Practice it