Skip to content
CurriculumChapter 20 · Pointers & Memory
IntermediateHigh focus~16 min

Pointer Arithmetic & Arrays

Pointer arithmetic is scaled by the pointed-to type. If p points to an int and int is four bytes, p + 1 advances by four bytes.

In plain English

Pointer arithmetic is walking down a street in steps the size of one house.

01

Scaling and array equivalence

Adding 1 to a pointer moves it by one element, not one byte. The compiler multiplies the integer offset by the size of the pointed-to type. An array name decays to a pointer to its first element in most expressions, so a[i] is equivalent to *(a + i). The pointer must stay within the array or one past its end.

chapter-20.cC
int a[4] = {10, 20, 30, 40};
int *p = a;

printf("%d\n", *p);       /* 10 */
printf("%d\n", *(p + 2)); /* 30 */
printf("%d\n", p[3]);     /* 40 */
02

Unary ++ and -- on pointers

The ++ and -- operators move a pointer forward or backward by one element. They are useful for walking an array, but they mutate the pointer itself. Keep a separate pointer if you still need the original base address. Postfix and prefix forms differ in when the old value is used, just like with integers.

chapter-20.cC
int a[3] = {5, 10, 15};
int *p = a;

printf("%d\n", *p++);  /* prints 5, then p moves to a[1] */
printf("%d\n", *p);    /* 10 */
printf("%d\n", *++p);  /* p moves to a[2], prints 15 */

Watch it happen

Step through the memory changes one instruction at a time.

step-by-step

Step 1 of 6

Create the array

int a[4] = {10, 20, 30, 40}; stores four ints contiguously. Each int is 4 bytes here.

a[0] · 0x7ffc2000
10
a[1] · 0x7ffc2004
20
a[2] · 0x7ffc2008
30
a[3] · 0x7ffc200c
40
a[0]0x7ffc2000→10

Key takeaways

  • Pointer arithmetic moves in units of the pointed-to type.
  • a[i] is equivalent to *(a + i).
  • An array name decays to a pointer to its first element.
  • ++ and -- mutate the pointer itself.

Common pitfalls

  • Assuming p + 1 adds one byte.
  • Going outside the bounds of an array.
  • Losing the base pointer after incrementing it.

Key focus

  • Trace pointer values and dereferenced values step by step.
  • Know why a[i] equals *(a + i).

Quick check

0 / 2 answered

1. If int *p points to an int at address 1000 and int is 4 bytes, what is p + 1?

2. Which expression is equivalent to a[2]?