Mental model
Picture a row of identical lockers in a corridor. The first locker is a known distance from the door, and every locker is the same width. To reach locker 37 you do not open lockers 0 to 36 on the way: you multiply 37 by the locker width, add the distance to the first one, and walk straight there.
An array is that corridor in memory. It occupies one contiguous block of bytes, divided into equal-sized slots, one per element. Three numbers describe it completely:
- the base address, where slot 0 starts;
- the element size in bytes (4 for a 32-bit
int, 8 for adoubleor a 64-bit reference); - the length (or capacity): how many slots the block has.
The lab uses 4-byte integers starting at address 1000. Addresses in a real program are chosen by the
allocator and look like 0x7ffd3a2c1e40; the round numbers just keep the arithmetic readable.
The address formula
Element i starts at
address(i) = base + i × elementSize
With base 1000 and 4-byte elements, index 0 is at 1000, index 1 at 1004 and index 3 at 1012. Run the
Indexing and addresses preset and watch every get compute this before it reads: one multiplication,
one addition, then one memory access. The cost is the same for index 0 and index 999,999, which is
exactly what O(1) random access means.
The hardware helps: x86-64 and ARM64 addressing modes can scale an index by 1, 2, 4 or 8 inside a
single load instruction, so a[i] often compiles to one instruction plus the bounds check.
Why indices start at 0
With zero-based indices the index is the offset: element i is i elements past the start. One-based
indexing would need base + (i − 1) × size, an extra subtraction on every access (compilers can fold it
away, but the formula is less direct). Zero-based indices also make half-open ranges natural: the valid
indices of an array of length n are 0 ≤ i < n, the range [0, n) has exactly n elements, and two
adjacent ranges [a, b) and [b, c) share no index. Dijkstra's short note in the references argues the
point.
Several dimensions, briefly
The same idea extends to a grid stored row after row: element (r, c) of a matrix with cols columns
is at base + (r × cols + c) × size. The
multidimensional arrays lesson
covers row-major and column-major layout and jagged arrays.
Why a linked list cannot do this
A linked list also holds a sequence, but its nodes live wherever the allocator put them. Node 37's address is stored only inside node 36, whose address is stored inside node 35, and so on. Reaching index i means following i pointers: O(i), not O(1). Equal-sized, contiguous slots are the whole trick. They also make arrays cache friendly, since neighbours share cache lines; the contiguous storage lesson measures that with a simple cache model.
Size, capacity and valid indices
A raw array has a fixed length. Often only part of it holds meaningful data: a buffer of 8 slots in which the first 5 have been filled. Keep two numbers apart:
- capacity: the number of slots in the block (8);
- size: the number of slots in use, always a prefix
0 … size − 1(5).
Valid indices for reading and writing are 0 ≤ i < size, not < capacity. Slots 5 to 7 exist in
memory, but they hold nothing meaningful (zeros, or stale values from earlier). The lab's
get(5) in the first preset fails for that reason even though the address 1020 is perfectly computable.
The lab draws unused slots faded and marks size with a pin.
The four built-in dynamic arrays (List<T>, list, ArrayList, std::vector) are exactly this
pattern plus a growth policy; the
dynamic arrays lesson shows the growth.
Here capacity stays fixed, which is what you get from new int[8] and keep using with a separate
counter.
Bounds checks
What happens on a[i] with i outside the valid range depends on the language:
| Language | Out-of-range read or write | Negative index |
|---|---|---|
| C# | IndexOutOfRangeException (arrays), ArgumentOutOfRangeException (List<T>) |
same exception |
| Python | IndexError |
valid: a[-1] is the last element, a[-n] the first |
| Java | ArrayIndexOutOfBoundsException |
same exception |
| C++ | a[i] on a built-in array, std::array or std::vector: undefined behaviour; at(i) throws std::out_of_range |
undefined behaviour with [] |
The safe languages check every access against the array's length; the JIT removes the check when it can
prove the index is in range (a loop from 0 to Length − 1, for example). C++ trusts you with [] for
speed: an out-of-range access may read a neighbouring variable, crash, or appear to work. Sanitizers
(-fsanitize=address) and debug-mode standard libraries catch many of these; at() checks always.
Note that the runtime checks against the array's length, which is the capacity in our model. If you
keep a separate size, as the lab does, checking i < size is your job; the runtime would happily let
you read the stale slot 6 of an 8-slot buffer holding 5 elements. That is what the CheckIndex /
checkIndex / check_index helper in the listings does.
What the slots actually hold
"Equal-sized slots" holds in every language, but what goes in a slot differs:
| Values stored inline | References stored | |
|---|---|---|
| C# | int[], double[], arrays of any struct |
arrays of classes and string: each slot is a reference (8 bytes on 64-bit) |
| Java | int[], double[] and the other primitive arrays |
Integer[], String[], any object array |
| Python | array.array('i', …), bytes, bytearray |
list and tuple: each slot is a pointer to an object |
| C++ | everything: int[8], std::array<T, N>, std::vector<T> store T itself |
only if you store pointers, e.g. std::vector<std::unique_ptr<T>> |
With references, indexing is still O(1): the formula finds the slot, and the slot holds the object's
address. Reading the object then costs one more memory access, possibly far away. Python's list[i] is
O(1) for this reason, even though every element is a separate object.
Element sizes are fixed per type: int is 32 bits in C# and Java by specification; in C++ int is at
least 16 bits and 32 bits on every mainstream platform, and sizeof(T) gives the exact size.
std::array<int, 8> is exactly the built-in int[8] with a value-type interface.
Costs
| Operation | Time | Notes |
|---|---|---|
Read or write a[i] |
O(1) | one address computation and one access |
Compute address(i) |
O(1) | independent of i and of n |
| Allocate a block of n slots | O(n) | the four languages zero or default-initialize it (C++ new int[n] without () does not) |
| Find the length | O(1) | stored with the array (Length, len, length, size() or the type) |
| Insert or delete in the middle | O(n) | shifting; the next lessons cover it |
Space is n × elementSize plus a small header (C#, Java and Python store the length and a type pointer next to the data).
The teaching implementation
The listings are one small fixed-capacity array of int, written the same way in all four languages: a
buffer allocated once, a separate size, one shared bounds check, and AddressOf / address_of,
which computes base + index × elementSize. In C# and Java the multiplication is done in 64-bit
(long) so that a large index times a large element size cannot overflow; C++ uses std::size_t and
std::uintptr_t. Safe C#, Java and Python never reveal real addresses, so the function takes the base
as a parameter; it models the arithmetic the runtime performs. The same class also implements insert and
delete, which the
insert and delete lesson walks
through.
Common mistakes
- Checking against capacity instead of size. The slot exists, but its contents are meaningless.
- Off-by-one at the end. The last valid index is
n − 1;i <= nin a loop condition reads one slot too far (an exception in C#, Java and Python, undefined behaviour in C++). - Assuming Python's negative indices elsewhere.
a[-1]is the last element in Python and an error (or undefined behaviour) in the other three. - Thinking
liststores the numbers. A Python list of a million ints holds a million pointers plus a million int objects;array.array('i')holds the raw 4-byte values. - Overflowing the offset.
index * sizein 32-bit arithmetic can wrap for very large buffers; do it in 64-bit orsize_t.
Edge cases
- Capacity 0: a valid array with no valid index; every access fails the bounds check.
- Size 0 with capacity 8: memory is allocated, but still no valid index.
- Index exactly
size: invalid for get and set, valid as an insert position (the end). - Element size 1 (
byte[],bytearray,charbuffers): the address is simply base + i.
Worked practice
1. An array of 8-byte doubles starts at address 4096. Where does element 10 start, and where does it end?
Answer
Start: 4096 + 10 × 8 = 4176. It occupies bytes 4176 to 4183; element 11 starts at 4184.
2. An element of a 4-byte array is at address 1036 and the base is 1000. What is its index?
Answer
(1036 − 1000) / 4 = 9. Going from an address back to an index is the same formula solved for i, which is what pointer subtraction does in C++.
3. A buffer has capacity 8 and size 5. Which of get(4), get(5), insert(5, x) and insert(6, x) are valid?
Answer
get(4) (the last element) and insert(5, x) (append at the end). get(5) reads an unused slot, and
insert(6, x) would leave a hole at index 5.
4. Why is list[i] O(1) in Python even though list elements can be objects of different sizes?
Answer
The list does not store the objects; it stores one pointer per element, and all pointers have the same size. The formula finds the pointer in O(1); following it is one more access.
Summary
- An array is one contiguous block of equal-sized slots;
address(i) = base + i × elementSize. - That formula makes indexing O(1) for every index; linked structures need O(i) pointer hops.
- Zero-based indices make the index equal to the offset and ranges half-open.
- With a separate size, valid indices are
0 ≤ i < size, not< capacity. - C#, Java and Python check bounds and throw; C++
[]does not check (undefined behaviour),at()does. - Slots hold values (primitive and struct arrays, everything in C++) or references (object arrays, Python lists).