Pointers & Memory · beginner · ~10 min

Pointer arithmetic

Increment, compare, and subtract pointers correctly.

Lesson

Adding 1 to a T * advances it by sizeof(T) bytes — not by 1 byte. That's how p++ walks an array of any type correctly. Two pointers into the same array can be compared (<, ==) or subtracted (p - q gives the count of elements between them).

Comparing or subtracting pointers from different arrays is undefined behaviour.

Code examples

int a[5] = {10,20,30,40,50};
int *p = a;
int *end = a + 5;
while (p < end) { printf("%d ", *p); p++; }

Common mistakes

  • Thinking p + 1 advances by 1 byte (it advances by sizeof(*p)).
  • Going past the end and dereferencing — undefined behaviour even though computing one-past-the-end is allowed.