Skip to content
Codescope

Arrays in memory

One block, constant-time indexing, and O(n) insertion in the middle.

intro8 min6 steps

Before you start

An **array** is the simplest data structure there is: a block of memory with values packed side by side. That's it. Every other data structure gets compared to this one.

The magic of arrays is that they give you constant-time access to any element — arr[5000] and arr[0] take the same time — because the CPU can compute the exact address from the index. The cost is that inserting a value in the middle means shifting every element after it, which is slow.

This lesson visualises the block of memory, watches the address arithmetic for indexing, and shows why inserting is O(n) but appending is O(1).

int arr[5]

one block, elements packed side by side
contiguous block
[0]
10
0x100
[1]
20
0x104
[2]
30
0x108
[3]
40
0x10c
[4]
50
0x110

5 ints × 4 bytes = 20 bytes. Addresses increment by 4.

Step 1 of 6. One contiguous block. An array of 5 ints occupies 20 consecutive bytes: each int is 4 bytes, and they are packed side by side with no gaps. That contiguity is the single fact that explains everything else — why indexing is fast, why insertion is slow, and why cache performance is good.

01 / 06

Step 01 / 06

One contiguous block

An array of 5 ints occupies 20 consecutive bytes: each int is 4 bytes, and they are packed side by side with no gaps.

That contiguity is the single fact that explains everything else — why indexing is fast, why insertion is slow, and why cache performance is good.

array-memory.cC
int arr[5] = {10, 20, 30, 40, 50};// Indexing: base + i * sizeof(int)arr[0];   // base + 0 = 0x100  → 10arr[3];   // base + 12 = 0x10c → 40// Inserting at index 1: shift everything right// [10, 20, 30, 40, 50]// [10, 15, 20, 30, 40, 50]  ← 4 elements moved// Appending at the end: no shift// [10, 20, 30, 40, 50, 60]  ← 0 elements moved// Deleting at index 0: shift everything left// [20, 30, 40, 50]          ← 4 elements moved