M05 · Arrays

Array Layout and Indexing

An array is one block of memory cut into equal slots. Because every slot has the same size, the address of element i is a single multiplication and addition away, whatever i is. This lesson works through that formula, why indices start at 0, what a bounds check protects you from, and how the four languages lay their arrays out.

~30 minBeginnerC# · Python · Java · C++
Curriculum: M05 Arrays · 5 of 5 lessons available

You will be able to

  • Compute the byte address of any element from the base address, the index and the element size.
  • Explain why indexing an array is O(1) and why the same is not true of a linked list.
  • Tell size from capacity in a fixed buffer, and say which indices are valid.
  • Describe what happens on an out-of-range index in C#, Python, Java and C++.
  • Say which arrays store values inline and which store references, in each of the four languages.

Helpful before this lesson

  • M02 Memory Model — What a variable, a reference and a buffer really are, and why contiguous memory is fast.
  • M03 Big O — Count operations, describe growth, and tell worst-case, average and amortized costs apart.

Guidance only. Those modules are planned; the essentials are recapped here.

Visual walkthrough

The interactive visualizer needs JavaScript. The explanation and all four implementations below work without it.

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 a double or 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 <= n in 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 list stores 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 * size in 32-bit arithmetic can wrap for very large buffers; do it in 64-bit or size_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, char buffers): 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).

Full implementation

The fixed-capacity array in four languages, each checked against one shared fixture of get, set, insert, append and delete sequences (empty, full, capacity one, out-of-range indices, front, middle and end positions) including the exact number of elements shifted, and 2,000 random operation sequences compared with the built-in dynamic array (List<T>, list, ArrayList, std::vector) held to the same capacity.

namespace Bekadan.Dsa.Examples.Arrays;
 
/// <summary>
/// A fixed-capacity array of ints with a separate size, the way a stack-allocated
/// buffer or a preallocated int[] is used: the buffer never grows. Indexing is O(1);
/// insert and delete shift the tail and cost O(size - index). A full array rejects
/// inserts instead of reallocating (List&lt;T&gt; would grow here).
/// </summary>
public sealed class FixedArray
{
    private readonly int[] items;
    private int size;
 
    public FixedArray(int capacity) => items = new int[capacity];
 
    public int Size => size;
    public int Capacity => items.Length;
    /// <summary>Elements moved by Insert and Delete so far (for the lab and the tests).</summary>
    public int Shifts { get; private set; }
 
    /// <summary>Byte address of element <paramref name="index"/> in a block starting at <paramref name="baseAddress"/>.</summary>
    public static long AddressOf(long baseAddress, int index, int elementSize)
    {
        return baseAddress + (long)index * elementSize;
    }
 
    private void CheckIndex(int index)
    {
        if (index < 0 || index >= size) throw new ArgumentOutOfRangeException(nameof(index), $"Index {index} is outside 0..{size - 1}.");
    }
 
    public int Get(int index)
    {
        CheckIndex(index);
        return items[index];
    }
 
    public void Set(int index, int value)
    {
        CheckIndex(index);
        items[index] = value;
    }
 
    public void Append(int value) => Insert(size, value);
 
    public void Insert(int index, int value)
    {
        if (size == items.Length) throw new InvalidOperationException("The array is full.");
        if (index < 0 || index > size) throw new ArgumentOutOfRangeException(nameof(index), $"Index {index} is outside 0..{size}.");
        for (int j = size - 1; j >= index; j--)
        {
            items[j + 1] = items[j]; // from the end backwards: nothing is overwritten before it is copied
            Shifts++;
        }
        items[index] = value;
        size++;
    }
 
    public int Delete(int index)
    {
        CheckIndex(index);
        int removed = items[index];
        for (int j = index; j < size - 1; j++)
        {
            items[j] = items[j + 1]; // from the gap forwards
            Shifts++;
        }
        items[size - 1] = 0; // clear the stale copy (matters for reference types: lets the GC collect it)
        size--;
        return removed;
    }
 
    public int[] ToArray() => items[..size];
}

Tested on .NET 10 (SDK 10.0.403), C# 14 · examples/csharp/Bekadan.Dsa.Examples/Arrays/FixedArray.cs

"""A fixed-capacity array with a separate size.
 
The buffer is allocated once and never grows. Indexing is O(1); insert and
delete shift the tail and cost O(size - index). A full array rejects inserts
instead of reallocating (a Python list would grow here). Python lists hold
references, so the address arithmetic below describes the list's pointer
array, or a typed buffer such as array.array('i').
"""
 
 
class ArrayFullError(Exception):
    """Raised by insert/append when size == capacity."""
 
 
def address_of(base: int, index: int, element_size: int) -> int:
    return base + index * element_size
 
 
class FixedArray:
    def __init__(self, capacity: int) -> None:
        self._items = [0] * capacity  # allocated once
        self._size = 0
        self.shifts = 0  # elements moved by insert and delete (for the lab and the tests)
 
    @property
    def size(self) -> int:
        return self._size
 
    @property
    def capacity(self) -> int:
        return len(self._items)
 
    def _check_index(self, index: int) -> None:
        if index < 0 or index >= self._size:
            raise IndexError(f"index {index} is outside 0..{self._size - 1}")
 
    def get(self, index: int) -> int:
        self._check_index(index)
        return self._items[index]
 
    def set(self, index: int, value: int) -> None:
        self._check_index(index)
        self._items[index] = value
 
    def append(self, value: int) -> None:
        self.insert(self._size, value)
 
    def insert(self, index: int, value: int) -> None:
        if self._size == len(self._items):
            raise ArrayFullError("the array is full")
        if index < 0 or index > self._size:
            raise IndexError(f"index {index} is outside 0..{self._size}")
        for j in range(self._size - 1, index - 1, -1):
            self._items[j + 1] = self._items[j]  # from the end backwards
            self.shifts += 1
        self._items[index] = value
        self._size += 1
 
    def delete(self, index: int) -> int:
        self._check_index(index)
        removed = self._items[index]
        for j in range(index, self._size - 1):
            self._items[j] = self._items[j + 1]  # from the gap forwards
            self.shifts += 1
        self._items[self._size - 1] = 0  # drop the stale reference
        self._size -= 1
        return removed
 
    def to_list(self) -> list[int]:
        return self._items[: self._size]

Tested on CPython 3.14.0 · examples/python/dsa_examples/fixed_array.py

package dev.bekadan.dsa.arrays;
 
import java.util.Arrays;
 
/**
 * A fixed-capacity array of ints with a separate size: the buffer is allocated
 * once and never grows. Indexing is O(1); insert and delete shift the tail and
 * cost O(size - index). A full array rejects inserts instead of reallocating
 * (ArrayList would grow here).
 */
public final class FixedArray {
    private final int[] items;
    private int size;
    private int shifts;
 
    public FixedArray(int capacity) {
        items = new int[capacity];
    }
 
    public int size() {
        return size;
    }
 
    public int capacity() {
        return items.length;
    }
 
    /** Elements moved by insert and delete so far (for the lab and the tests). */
    public int shifts() {
        return shifts;
    }
 
    /** Byte address of element {@code index} in a block starting at {@code base}. */
    public static long addressOf(long base, int index, int elementSize) {
        return base + (long) index * elementSize;
    }
 
    private void checkIndex(int index) {
        if (index < 0 || index >= size) {
            throw new IndexOutOfBoundsException("Index " + index + " out of bounds for size " + size);
        }
    }
 
    public int get(int index) {
        checkIndex(index);
        return items[index];
    }
 
    public void set(int index, int value) {
        checkIndex(index);
        items[index] = value;
    }
 
    public void append(int value) {
        insert(size, value);
    }
 
    public void insert(int index, int value) {
        if (size == items.length) {
            throw new IllegalStateException("The array is full");
        }
        if (index < 0 || index > size) {
            throw new IndexOutOfBoundsException("Index " + index + " out of bounds for insert at size " + size);
        }
        for (int j = size - 1; j >= index; j--) {
            items[j + 1] = items[j]; // from the end backwards (System.arraycopy handles the overlap the same way)
            shifts++;
        }
        items[index] = value;
        size++;
    }
 
    public int delete(int index) {
        checkIndex(index);
        int removed = items[index];
        for (int j = index; j < size - 1; j++) {
            items[j] = items[j + 1]; // from the gap forwards
            shifts++;
        }
        items[size - 1] = 0; // clear the stale copy (for objects: null, so the GC can collect it)
        size--;
        return removed;
    }
 
    public int[] toArray() {
        return Arrays.copyOf(items, size);
    }
}

Tested on Java 25 (Temurin 25.0.5); also compiles on Java 17 · examples/java/src/main/java/dev/bekadan/dsa/arrays/FixedArray.java

#pragma once
 
#include <cstddef>
#include <cstdint>
#include <stdexcept>
#include <vector>
 
namespace bekadan::dsa {
 
// A fixed-capacity array of ints with a separate size: the buffer is allocated
// once and never grows (the idea behind C++26 std::inplace_vector). Indexing is
// O(1); insert and erase shift the tail and cost O(size - index). A full array
// throws instead of reallocating (std::vector would grow here).
 
inline std::uintptr_t address_of(std::uintptr_t base, std::size_t index, std::size_t element_size) {
    return base + index * element_size;
}
 
class FixedArray {
public:
    explicit FixedArray(std::size_t capacity) : items_(capacity) {}  // allocated once, never resized
 
    std::size_t size() const { return size_; }
    std::size_t capacity() const { return items_.size(); }
    // Elements moved by insert and erase so far (for the lab and the tests).
    std::size_t shifts() const { return shifts_; }
 
    int get(std::ptrdiff_t index) const {
        check_index(index);
        return items_[static_cast<std::size_t>(index)];
    }
 
    void set(std::ptrdiff_t index, int value) {
        check_index(index);
        items_[static_cast<std::size_t>(index)] = value;
    }
 
    void append(int value) { insert(static_cast<std::ptrdiff_t>(size_), value); }
 
    void insert(std::ptrdiff_t index, int value) {
        if (size_ == items_.size()) throw std::length_error("the array is full");
        if (index < 0 || index > static_cast<std::ptrdiff_t>(size_)) throw std::out_of_range("insert index out of range");
        const auto at = static_cast<std::size_t>(index);
        for (std::size_t j = size_; j > at; --j) {
            items_[j] = items_[j - 1];  // from the end backwards (std::move_backward does the same)
            ++shifts_;
        }
        items_[at] = value;
        ++size_;
    }
 
    int erase(std::ptrdiff_t index) {
        check_index(index);
        const auto at = static_cast<std::size_t>(index);
        const int removed = items_[at];
        for (std::size_t j = at; j + 1 < size_; ++j) {
            items_[j] = items_[j + 1];  // from the gap forwards
            ++shifts_;
        }
        items_[size_ - 1] = 0;  // clear the stale copy (for class types: destroy or reset it)
        --size_;
        return removed;
    }
 
    std::vector<int> to_vector() const { return {items_.begin(), items_.begin() + static_cast<std::ptrdiff_t>(size_)}; }
 
private:
    void check_index(std::ptrdiff_t index) const {
        if (index < 0 || index >= static_cast<std::ptrdiff_t>(size_)) throw std::out_of_range("index out of range");
    }
 
    std::vector<int> items_;
    std::size_t size_ = 0;
    std::size_t shifts_ = 0;
};
 
}  // namespace bekadan::dsa

Tested on C++23, GCC 15.3 (libstdc++) · examples/cpp/include/bekadan/dsa/fixed_array.hpp

References