No history yet

Array Memory Layout

Arrays in Memory

When you declare a variable like int score = 100;, you ask the computer to set aside a small piece of memory to hold that value. An array does something similar, but for a whole collection of values. The key difference is that an array reserves a single, unbroken block of memory for all its elements.

Think of it like a row of connected mailboxes. Each box can hold one item, and they're all lined up one after the other. This is called , and it’s what makes arrays fast and efficient. Because the elements are neighbors in memory, the computer doesn't have to hunt around to find them.

Lesson image

In C++, you declare a fixed-size array by specifying the data type, the array's name, and the number of elements it will hold inside square brackets. This number must be known when you write the code.

// Declares an array named 'high_scores' that can hold 5 integers.
int high_scores[5];

When this line of code runs, the system reserves a block of memory large enough for five integers. If one int takes up 4 bytes, this array will occupy a 20-byte block (5 elements × 4 bytes/element).

Accessing Elements

To get to an element, you use its index, which is its position in the array. In C++ and many other languages, array indexing starts at zero. The first element is at index 0, the second at index 1, and so on. For an array of 5 elements, the valid indices are 0, 1, 2, 3, and 4.

This [{}] isn't arbitrary. It comes directly from how memory addresses are calculated.

The computer knows the starting memory location of the array, often called the base address. To find any other element, it uses a simple formula. It takes the base address and adds an offset, which is the index multiplied by the size of one element.

element_address=base_address+(index×element_size)\text{element\_address} = \text{base\_address} + (\text{index} \times \text{element\_size})

Let's use our high_scores array as an example. Suppose its base address is 0x1000 and each int is 4 bytes.

To find the element at index 2 (high_scores[2]):

  • Address = 0x1000 + (2 × 4 bytes)
  • Address = 0x1000 + 8 bytes
  • Address = 0x1008

The computer jumps directly to memory address 0x1008 to read or write the value. This direct calculation is why accessing any element in an array takes the same amount of time, regardless of its position.

Quiz Questions 1/5

What is the defining characteristic of how an array stores its elements in memory?

Quiz Questions 2/5

Which of the following correctly declares a C++ array that can hold 10 floating-point numbers?