Pointers & Memory · beginner · ~10 min

Pointer arithmetic

Increment, compare, and subtract pointers correctly.

Lesson

How adding to a pointer works

When you add 1 to a pointer of type T *, the pointer does not move forward by one byte. It moves forward by sizeof(T) bytes — the size of one element.

This is what makes p++ walk through an array of any type correctly. Each step lands exactly on the next element, whatever its size.

Example: if int is 4 bytes, then for an int *p, writing p + 1 moves the address forward by 4 bytes, not 1.

Comparing and subtracting pointers

Two pointers that point into the same array can be:

  • Compared with operators like < and ==.
  • Subtracted: p - q gives the number of elements between them (not the number of bytes).

When it is undefined behaviour

Comparing or subtracting pointers that point into different arrays is undefined behaviour. Undefined behaviour means the C standard places no requirements on what happens — the result is not reliable, so never do it.

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

  • Assuming p + 1 advances by one byte. It actually advances by sizeof(*p) — the size of one element.
  • Going past the end and dereferencing it. Computing a one-past-the-end pointer is allowed, but reading or writing through it is undefined behaviour.

Summary

  • Adding 1 to a T * moves it forward by sizeof(T) bytes, so p++ steps to the next element.
  • Pointers into the same array can be compared (<, ==) and subtracted; p - q counts elements between them.
  • Comparing or subtracting pointers from different arrays is undefined behaviour.
  • You may compute a one-past-the-end pointer, but never dereference it.

Practice with these exercises