A girl and a robot thinking together

Think together · Start with a story

A girl draws a row of boxes for an array, and the robot asks what makes the row a helpful picture of memory.

Break down the process

Follow the numbered steps, then explain them in your own words
  1. Array startFirst element
  2. Next elementRight next to it
  3. ContinueOne after another

The elements of an ordinary C++ array are stored contiguously in memory.

01Why is it useful to draw an array as a row?

A row makes it easy to picture that elements have an order and that each one has a position.

02What does “contiguous” mean?

Contiguous means that array elements are stored one after another without gaps between them.

The address difference between neighboring elements is the size of one element.

03Why can you find array elements quickly?

Because the program can calculate an element's location from the starting location and its index.

element location = start location + index × element size

This lets the program reach an element directly instead of checking every earlier one.

04Is an array name a pointer?

Do not simply say “an array is a pointer.”

An array is a real object type that contains a fixed number of elements.

However, in many expressions, an array name undergoes array-to-pointer conversion and becomes a pointer to its first element.

05What are the benefits of contiguous storage?

Index lookup

The element's location can be calculated quickly.

Convenient traversal

Visiting elements one by one is natural.

Cache-friendly

Modern CPUs can often use nearby data efficiently.

06How do you calculate an array’s total size?

int a[10];

The total space used by an array object is:

number of elements × size of each element

In code, you can write:

sizeof(a)

This gives the number of bytes occupied by the entire array object.

What you have learned

  • Elements of an ordinary C++ array are stored contiguously in memory.
  • The address difference between neighboring elements equals the size of one element.
  • Contiguous storage makes index lookup and traversal efficient.
  • An array is not a pointer, but in many expressions it converts to a pointer to its first element.
  • sizeof(array) gives the size of the whole array object.

Next: Why Do Array Indexes Start at 0?

Your turn to try

If each element in an example uses 4 bytes, how many bytes from the start is index 2?

Ready? Open to see the explanation

8 bytes: you move past 2 elements, each 4 bytes. The size of 4 bytes is given as a condition in this example.