Lesson 19: Pointer arithmetic & arrays
You can do arithmetic on pointers — but smart arithmetic: p + 1 doesn't advance by one byte, it advances by one whole element, i.e. by sizeof(type) bytes. Here the big secret of arrays is revealed: an array name 'decays' to the address of its first element — arr is exactly &arr[0]. From this follows
An array is a row of adjacent boxes on a street. The array's name is the address of the first box, and p + 1 means 'hop to the next box' — no matter how many centimeters wide each box is, the hop is always exactly one whole box.
- pointer arithmetic
- Adding and subtracting on pointers. p + 1 advances to the next element, not the next byte.
- element step
- p + 1 adds sizeof(type) bytes to the address — for int (4 bytes): from 1000 to 1004.
- array decay
- In most expressions, an array name becomes the address of its first element: arr == &arr[0].
- the identity arr[i] == *(arr + i)
- Indexing is shorthand for arithmetic: hop i elements from the start and access the value.
- pointer walking
- A loop that advances a pointer across the array: while (p < arr + n) { ...; p++; }.