What is an Array
An array is the simplest and most fundamental data structure. It's a collection of elements stored side by side in memory, like books arranged on a shelf. Each element has a number (called an index) that identifies its position, starting from zero.
int grades[5] = {85, 92, 78, 95, 88};// [0] [1] [2] [3] [4]Arrays guarantee that all elements live in contiguous memory, one continuous block with no gaps between elements. Almost everything about their performance follows from that property.
The bookshelf analogy
Imagine a bookshelf where each slot is exactly the same width. If you know a book is in slot #7, you don't need to count from the beginning; you reach directly to that position. Arrays work the same way: the computer calculates exactly where each element lives and jumps straight to it.
Why Arrays are fast
When you ask for grades[3], the computer doesn't search through the array. Instead, it does a simple calculation:
address = start + (index × size of each element)
If the array starts at memory address 1000 and each integer takes 4 bytes, then element [3] is at address 1000 + (3 × 4) = 1012. That's one calculation and one memory access, so array access is . It takes the same time whether your array has 10 elements or 10 million.
grades[]: 85, 92, 78, 95
The index is an offset
Look at the formula again: the index isn't a position you count to, it's how many elements to skip from the start. grades[3] means "start at the beginning of the array and skip 3 elements", which lands on the fourth one. The first element skips nothing, so its index is 0.
That's why most languages count from zero. In C this is literal: grades[3] is defined as *(grades + 3), the value at the start address moved forward by 3 elements. Starting at 1 would mean subtracting 1 on every access, or wasting the first slot.
Why the type comes first
The formula needs one more thing besides the index: the size of each element. That's what the type in a declaration gives the compiler. int grades[5] says each slot is the size of an int, so the compiler knows to move 4 bytes per index and to reserve 5 × 4 bytes for the whole array:
int grades[5]; // 5 × 4 bytesdouble prices[5]; // 5 × 8 byteschar letters[5]; // 5 × 1 byteprintf("%zu %zu %zu\n", sizeof grades, // 20 sizeof prices, // 40 sizeof letters); // 5Same length, three different sizes. Without the type, the compiler couldn't reserve the memory or turn prices[3] into an address. Languages where you never declare the type still have to settle this somewhere, and Arrays: Go vs JavaScript shows what JavaScript pays for leaving it open.
The cache advantage
Modern CPUs fetch more than the byte you asked for. They grab a whole chunk of nearby memory and store it in a fast "cache" close to the processor. When your data is contiguous like in an array, accessing one element often brings its neighbors into cache for free.
That's why iterating through an array in order is so fast: by the time you need an element, it's probably already in cache. Scattered data structures like linked lists lose this advantage, as each element might be anywhere in memory.
The price of simplicity
The same contiguous layout also makes some operations expensive.
The insertion problem
To insert a value in the middle of an array, every element after that position has to shift one slot to the right to make room. Inserting at position 0 shifts the entire array.
Before: [85, 92, 78] · After: [85, 90, 92, 78]
For an array with a million elements, inserting at the beginning means moving a million elements. That's , the worst case for insertion.
The fixed size dilemma
When you create an array, you must decide its size upfront. Too small, and you run out of space. Too large, and you waste memory.
You also can't just extend an array that ran out of room. The bytes right after the last element may already belong to another variable, another array or another program's data, and the array has to stay contiguous. The only general way to get a bigger array is to allocate a new block somewhere with enough free space, copy every element into it and release the old one. Copying n elements makes that , no matter how many slots you were adding.
Static vs dynamic Arrays
Static Arrays: fixed at birth
In C, when you write int numbers[100], you're asking the compiler to reserve exactly 100 integer slots. This memory comes from the "stack", a fast, automatically managed region that gets cleaned up when your function returns.
void process_grades() { int grades[30]; // Space for exactly 30 grades // Use the array...} // Memory automatically freed hereStatic arrays are simple and fast, but inflexible. If 31 students show up, you're out of luck.
Dynamic Arrays: growing on demand
The alternative is to allocate memory from the "heap", a larger region where you decide when memory is allocated and freed. In C, this means using malloc:
int *grades = malloc(30 * sizeof(int)); // Start with 30 slots// Later, if you need more...grades = realloc(grades, 60 * sizeof(int)); // Double the spaceManaging this by hand is tedious and error-prone, so most languages provide dynamic arrays that grow automatically: std::vector in C++, ArrayList in Java, list in Python, or plain arrays in JavaScript.
JavaScript arrays go further than the others: you don't declare their size or their element type at all. Arrays: Go vs JavaScript looks at what that costs in memory, using Uint32Array as the comparison.
How dynamic Arrays grow
When a dynamic array fills up, it typically doubles its capacity instead of adding a single slot, copies all elements to the new larger space, and frees the old memory.
Doubling balances wasted space against copying overhead. If you grew by one element each time, you'd copy the entire array on every insertion. Doubling keeps the average cost of insertion constant, even though occasional insertions trigger expensive resize operations.
The math of doubling
Imagine inserting 1000 elements into an array that starts with capacity 1:
- Copy 1 element when growing to capacity 2
- Copy 2 elements when growing to capacity 4
- Copy 4 elements when growing to capacity 8
- ...and so on until capacity 1024
Total copies: 1 + 2 + 4 + 8 + ... + 512 = 1023
That's roughly n copies for n insertions, an average of about 1 copy per insertion. This is called amortized O(1) time.
- Append
- Append that resizes
- Average cost per append
Common operations and their costs
Each operation's cost follows from the contiguous layout:
| Operation | Time | Why |
|---|---|---|
| Access by index | O(1) | Direct calculation to memory address |
| Update by index | O(1) | Same as access, but writes instead of reads |
| Insert at end | O(1)* | Just place element (if space available) |
| Insert at beginning | O(n) | Must shift all elements right (JS unshift) |
| Insert in middle | O(n) | Must shift elements after insertion point |
| Delete from end | O(1) | Just decrease the size counter |
| Delete from beginning | O(n) | Must shift all elements left (JS shift) |
| Search (unsorted) | O(n) | Must check each element |
| Search (sorted) | O(log n) | Binary search cuts space in half each step |
*For dynamic arrays, occasional resizing makes this "amortized O(1)"
Try it yourself
Now that you know the cost of each operation, try them yourself: insert at any index, delete one, or access an element directly.
Keyboard and mouse
- M
- sound on or off
- F
- fullscreen
- R
- reset
- Space+drag
- move the canvas
- Ctrl+scroll
- zoom
- every operation you run shows up here
Multi-dimensional Arrays
Arrays can have multiple dimensions, creating grids, cubes, or even higher-dimensional structures.
2D Arrays: tables and matrices
A 2D array is like a spreadsheet, with rows and columns. In memory, it's still stored as a single contiguous block, typically in "row-major order" (all of row 0, then all of row 1, etc.).
int matrix[3][4] = { {1, 2, 3, 4}, // Row 0 {5, 6, 7, 8}, // Row 1 {9, 10, 11, 12} // Row 2};As the table you index
As it sits in memory
Row by row, each element sits 4 bytes after the previous one: the loop reads memory straight through. Hover a cell to replay the loop up to it, or click to keep it.
Hover any cell in the table: the trail shows the order the elements really sit in memory, all of row 0 and then row 1, so matrix[1][0] comes right after matrix[0][3]. Then switch the figure between row by row and column by column: the numbers show the order each loop visits the elements.
Why loop order matters
Both loops below add up the same 4096 × 4096 matrix of ints and do the same arithmetic. The only difference is which index changes in the inner loop.
// Row by row: the inner loop walks along a rowfor (int row = 0; row < N; row++) for (int col = 0; col < N; col++) sum += matrix[row][col];// Column by column: the inner loop walks down a columnfor (int col = 0; col < N; col++) for (int row = 0; row < N; row++) sum += matrix[row][col];As the cache section described, the CPU never reads a single int from memory. It loads a whole cache line, 64 bytes on most current processors, which is 16 ints at once. Row by row, one load serves the read that caused it and the next 15. Column by column, consecutive reads are a whole row apart (16 KB here, since each row holds 4096 four-byte ints), so every read lands on a different line, and by the time the loop comes back for the next column most of those lines have already been pushed out of the cache.
I measured both loops on an AMD Ryzen 7 9800X3D, compiled with GCC 13 at -O2: row by row took about 3.4 ms and column by column about 75 ms, roughly 20 times slower for the same work. Turning off auto-vectorization (-fno-tree-vectorize) didn't close the gap, so it comes from memory access, not from the compiler.
Nothing makes row-major faster in itself. C and C++ use it, so there the fast loop is the one whose last index changes in the inner loop. Fortran, MATLAB and Julia store matrices column-major, with each column contiguous, and in those languages the column-by-column loop is the fast one. NumPy creates arrays in C order unless you pass order='F'. In every case, the inner loop should move along the index the language stores next to each other.
Arrays in the real world
Arrays are everywhere in computing:
- Images are 2D arrays of pixels
- Audio is an array of amplitude samples over time
- Text strings are arrays of characters
- Databases use arrays internally for columnar storage
- Graphics cards process arrays of vertices and pixels in parallel
The array's simplicity and predictable memory access patterns make it the default choice when you need to store a sequence of similar items.
When Arrays fall short
Some workloads fit other structures better:
Need frequent insertions/deletions in the middle? Consider a linked list, which can insert or delete in O(1) if you have a reference to the position.
Need fast lookups by value? A hash table provides O(1) average-case lookups, while unsorted arrays require O(n).
Need to maintain sorted order with frequent changes? A balanced tree (like a red-black tree) keeps elements sorted while supporting O(log n) insertions and deletions.
Unknown or highly variable size? While dynamic arrays handle this, if size changes dramatically (like from 10 to 10,000 back to 10), you might want a structure that releases memory more eagerly.
Summary
An array is a continuous block of memory with indexed access. That layout gives it:
- Constant-time access to any element through the index calculation
- Cache-friendly sequential access
- Minimal overhead: just the data, with no extra pointers or metadata
- Predictable performance, with no worst cases hiding in normal operations
The cost is rigidity. Growing an array means copying it, and inserting or deleting anywhere but the end means shifting elements. When you choose a data structure, fast access against flexible modification is usually the first tradeoff you weigh.
Most other data structures either build on arrays or work around their limits. Linked lists give up access speed for cheaper insertion. Hash tables use arrays internally and add a layer of indirection. Trees organize data hierarchically but often store nodes in array-backed memory pools.