Skip to the workspace
Pebellslearn by building
Data Structures in Memory  ›  Lesson

Arrays — One Block of Memory

Array 12 minAn array stores its elements side by side in one block of memory, so the address of any element is the start address plus the index times the element size.

computer science / Arrays — One Block of Memory

Explore each scene at your own pace.

01 · The rule

The rule

Arrays — One Block of Memory

A computer's memory is one enormous row of numbered boxes, each holding one byte. When you ask for scores[700], the machine does not count through 700 scores to get there. It works out exactly where the 701st score lives and goes straight to it. That trick is the whole reason arrays are the most common data structure in computing.

The rule

Address = start + index × size. One sum, any element.

An array reserves one unbroken block of memory and puts its elements side by side, all the same size. Three numbers are enough to find any element:

  • start: the address where the block begins,
  • index: which element you want, counting from 0,
  • size: how many bytes one element takes.

Say an array of 4-byte integers starts at address 1000:

address:  1000   1004   1008   1012   1016
index:      0      1      2      3      4
value:     42     17     99      8     63

Element 3 is at 1000 + 3 × 4 = 1012. This also explains why most languages count from 0: the index is really an offset, and the first element is zero steps from the start.

The same layout has a cost. Because elements must stay packed together in order, putting a new value at the front or in the middle means shifting everything after it one slot to the right. And if the block is full, a growing array (a Python list, a Java ArrayList) has to find a bigger block and copy everything across.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.