5.1.11 · D3C Programming

Worked examples — Multi-dimensional arrays

2,573 words12 min readBack to topic

The scenario matrix

Every worked example below is tagged with a cell so you can see the coverage is complete.

Cell Case class What makes it tricky Example
A Interior element a[i][j], both indices > 0 plain formula Ex 1
B First element a[0][0] zero offset — does base survive? Ex 2
C Last element a[R-1][C-1] biggest offset, must equal size−1 element Ex 2
D Degenerate: single row a[1][N] or single column a[N][1] "is it still 2D?" Ex 3
E 3D element a[i][j][k] product-to-the-right rule Ex 4
F Pointer arithmetic reading (a+i vs *a+i) row-jump vs element-jump Ex 5
G Type/decay twist: sizeof on a, a[i], a[i][j] which dimension survives decay Ex 6
H Real-world word problem modelling a grid Ex 7
I Exam trap: a[1,2] comma operator language gotcha Ex 8
J Boundary: reading one-past-the-row (a[0][C] aliases a[1][0]) limiting/overflow index Ex 9

Ten cells, nine examples (Ex 2 covers both B and C — the extremes of one array). Let's go.











Recall Quick self-test (reveal each)

Offset (in elements) of a[2][3] in int a[4][5]? ::: . &a[0][0] compared to (int*)a? ::: Identical — first element sits at the base. Offset of last element a[3][4] in int a[4][5]? ::: elements = bytes past base. a+1 vs *a+1 for int a[3][4], base 1000 — the two addresses? ::: (a full row) and (one int). sizeof(a), sizeof(a[0]), sizeof(a[0][0]) for int a[3][4]? ::: , , bytes. Offset of a[1][2][3] in int a[2][3][4]? ::: elements. What does a[1,2] mean? ::: The comma operator gives a[2] — a whole row pointer, not a single int. Which valid element does a[0][4] alias in int a[3][4]? ::: a[1][0] (both at offset 4).


Connections

  • Multi-dimensional arrays — the parent: storage, formula, pointer identity.
  • C Arrays (1D) — the degenerate single-row/column cases collapse to this.
  • Pointers in C — Ex 5's a+i vs *a+i is pure pointer arithmetic.
  • Array Decay — why a becomes int(*)[4] (Ex 5, Ex 6).
  • Pointer to Array vs Array of Pointers — the int(*)[4] type in Ex 5.
  • sizeof Operator — Ex 6 in full.
  • Row-major vs Column-major — why offsets use (Ex 1–4, 9).
  • Variable Length Arrays (C99) — passing these grids to functions.