5.1.10 · D3C Programming

Worked examples — Arrays and pointers — array name decays to pointer

2,365 words11 min readBack to topic

For every example below we assume a typical machine where int is 4 bytes and a pointer is 8 bytes (64-bit). If your machine differs, only the numbers scale — the reasoning is identical.


The scenario matrix

Every case this topic can throw at you falls into one of these cells. Each worked example is tagged with the cell(s) it covers.

# Cell class What makes it tricky Covered by
A Plain decay in a value expression array name → T* silently Ex 1
B sizeof exception (no decay) you get whole-array bytes Ex 1, Ex 2
C &arr exception (no decay) type becomes T(*)[N], +1 jumps far Ex 3
D Passing to a function (size lost) int a[] param is really int* Ex 4
E arr[i] == *(arr+i) == i[arr] identity commutativity of + Ex 5
F 2-D / multidimensional decay only the outermost dimension peels off Ex 6
G char[] vs char* string literal initialiser is the 3rd exception Ex 7
H Degenerate / edge inputs 1-element array, sizeof of a param, &arr[0] vs arr Ex 8
I Real-world word problem sum a sensor buffer safely Ex 9
J Exam-style twist sizeof(a)/sizeof(a[0]) element count trick Ex 10

We will now hit every cell.


Worked Examples

Figure — Arrays and pointers — array name decays to pointer


Figure — Arrays and pointers — array name decays to pointer



Figure — Arrays and pointers — array name decays to pointer





Recall Quick self-test over the whole matrix

sizeof(a) for int a[10]? ::: 40 (no decay, whole array). sizeof(p) for int *p = a;? ::: 8 (pointer width). Type m decays to for int m[3][4]? ::: int(*)[4], not int**. sizeof(m) for int m[3][4]? ::: 48 bytes (). sizeof(s) for char s[]="hi";? ::: 3 (h, i, \0). sizeof(t) for char *t="hi";? ::: 8 (pointer). Element count of int a[10] inside g(int a[])? ::: 2 on a 64-bit machine (8/4) — the trap; decay lost the size. q+1 for int(*q)[5] at base 1000? ::: 1020 (steps 20 bytes = whole 5-int array). Sum of {21,22,20,23,25,24,22,21}? ::: 178.



Connections

  • Pointer Arithmetic — why p+1 and q+1 step different byte distances (Ex 3, 6).
  • Passing Arrays to Functions — the lost-size fallout (Ex 4, 9, 10).
  • sizeof Operator — the #1 no-decay exception, used in every example.
  • Multidimensional Arrays — decay peels only the outer dimension (Ex 6).
  • Strings in Cchar[] vs char* and literal decay (Ex 7).
  • Memory Layout and Addresses — contiguous boxes underlie every stride computation.