5.1.9 · D3C Programming

Worked examples — Pointer arithmetic — adding integers to pointers

2,725 words12 min readBack to topic

This page is the "hands dirty" companion to Pointer arithmetic — adding integers to pointers (index 5.1.9). We take the single rule from the parent —

— and drive it through every situation it can produce: positive steps, negative steps, the zero step, one-past-the-end, tiny char strides, fat double strides, casting to change the stride, a word problem, and an exam trap. Nothing here is new rule; everything is that one rule reused, exactly as the parent's 80/20 sentence promised.

Before we start, three plain-word reminders so no symbol is unearned:


The scenario matrix

Every pointer-arithmetic question is one (or a combo) of these cells. The worked examples below are each tagged with the cell they hit, and together they touch every row.

# Case class What is special Example
A Positive step, int* ordinary forward move Ex 1
B Negative step subtract lands you behind Ex 2
C Zero step p + 0 degenerate case Ex 2
D char* stride = 1 smallest possible stride Ex 3
E double* stride = 8 largest common stride Ex 3
F Cast changes stride same address, new lens Ex 4
G One-past-the-end limit legal to form, illegal to deref Ex 5
H Walking with p++ loop / accumulate Ex 6
I i[arr] commutativity twist exam gotcha Ex 7
J Precedence *p+1 vs *(p+1) operator-binding trap Ex 8
K Word problem (real memory layout) translate English → arithmetic Ex 9

The address picture we will reuse

Every example below is a walk along the same idea: a row of equal-width boxes in memory. Keep this figure in your head.

Figure — Pointer arithmetic — adding integers to pointers

Look at the picture: each box is sizeof(T) bytes wide, boxes sit back-to-back (arrays are contiguous — see Arrays decay to pointers), and the pointer's +1 always lands you cleanly on the next box's left edge, never halfway inside a box.


Ex 1 — Positive step, int* (Cell A)


Ex 2 — Negative step and the zero step (Cells B & C)


Ex 3 — Smallest stride vs largest stride (Cells D & E)


Ex 4 — Casting changes the stride mid-flight (Cell F)


Ex 5 — The one-past-the-end limit (Cell G)


Ex 6 — Walking an array with p++ (Cell H)


Ex 7 — The i[arr] commutativity twist (Cell I)


Ex 8 — Precedence: *p + 1 vs *(p + 1) (Cell J)


Ex 9 — Word problem: laying out a record buffer (Cell K)


Recall

Recall Which cell is each expression?

p + 0 (int*) ::: Cell C — zero step, p unchanged. ((char*)p) + 1 ::: Cell F — cast changes stride to 1 byte. a + N for int a[N] ::: Cell G — one-past-the-end, legal to form, not to deref. 3[a] ::: Cell I — commutativity; equals a[3]. *p + 1 ::: Cell J — precedence; (*p)+1, not *(p+1).


Connections