Lesson 90 +10 XP

Pointer Arithmetic

Pointer Arithmetic

Pointers support math: add, subtract, compare - it's how arrays and walk through memory.

Adding moves forward

int a[] = {10, 20, 30};
int *p = a;          // 0
printf("%d", *p);    // 10
p++;
printf("%d", *p);    // 20
p++;
printf("%d", *p);    // 30

Each p++ moves to the next array element.

Subtracting moves backward

p--;   // points back to 20

Pointer difference

p - q gives the number of elements between two pointers

Why element-sized steps

A pointer knows its type. For int*, steps of index are sizeof(int) bytes apart, so the math stays correct on any machine.

TL;DR

  • p++ moves to the next element.
  • p + i is element i away from p.
  • p - q counts elements between pointers.
  • The compiler sizes each step per the type.