Course contentsShow
← C
Lesson 384 of 1,2196. Arrays and StringsFree lesson

Visualizing memory layout of arrays

Visualizing memory layout of arrays

What you'll learn: How C stores array elements as a single, unbroken chain of memory cells.

The Apartment Building Analogy

Imagine you want to book hotel rooms for a group of five friends. You could book five random rooms across different floors, but that would make it hard to find everyone. Instead, you request a block of five rooms in a single row on the same floor.

In C, an array is exactly like that block of rooms. When you declare an array, the computer doesn't just find five random spots in its memory; it looks for one single, continuous stretch of space large enough to hold the entire group.

Seeing the Layout

In memory, these elements live side-by-side. If the first element is at a specific "address" (like a room number), the second element is guaranteed to be right next to it. There is no empty space or "padding" between them.

Consider this array of integers:

#include <stdio.h>

int main() {
    // A block of 4 integers
    int scores[4] = {85, 92, 78, 90};
    
    // In memory, these look like:
    // [85][92][78][90]
    
    return 0;
}

If each int takes up 4 bytes of space, and our array starts at memory address 1000, the layout looks like this:

  • scores[0] is at address 1000
  • scores[1] is at address 1004
  • scores[2] is at address 1008
  • scores[3] is at address 1012

Why Contiguity Matters

This "side-by-side" layout is why C arrays are so fast. Because the computer knows the elements are in a perfect line, it doesn't have to "search" for scores[3]. It simply calculates: "Start at the beginning and skip ahead three spots."

This is also why arrays have a fixed size. Once you've reserved that specific block of "rooms" in memory, you can't easily add a sixth room if the space next to it is already occupied by another variable.

Key takeaway

An array is a contiguous block of memory where elements are stored in a single, unbroken sequence.