C Workshop · Pointer Arithmetic
Lesson C

Pointer Arithmetic

If p points at an array, p+1 is the next element, not plus one byte. *(p+1) is the same as p[1].

What it is

If p points at an array, p+1 is the next element, not plus one byte. The compiler scales by sizeof(the thing you point at). *(p+1) is the same as p[1].

Approach

  1. Point p at the first element (array name decays to a pointer).
  2. Add an integer to move to another index.
  3. Dereference to read that slot.

Where this is used in the real world

Diagram

1

p

a[0]=4

2

p+1

a[1]=5

3

*(p+1)

5

Run algorithm

Each step highlights the matching C line. Program output appears only when a line that prints actually runs.

Ready
C code
1#include <stdio.h>
2int main(void) {
3    int a[3] = {4, 5, 6};
4    int *p = a;
5    printf("%d\n", *(p + 1));
6    return 0;
7}
What this line does
Press Run algorithm. The highlight will move through the C code.
Program output
(no output yet)

Check your understanding

Five questions. Pick one answer each, then Check answers. The correct choice turns green.

1. *(p+1) with {4,5,6} is:

Next int.

2. p+1 is scaled by:

Pointer arithmetic.

3. p[1] compared to *(p+1):

Equivalent.

4. int *p = a; points at:

First element.

5. Another kind, p++ in a loop:

Walk the row.