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

The relationship between array size and memory

The relationship between array size and memory

What you'll learn: How C reserves a continuous block of memory based on your array's data type and length.

The "Hotel Row" Analogy

Imagine you are a hotel manager. When you declare a single variable, like int roomNumber;, you are booking one room. But when you declare an array, you are booking a specific number of rooms that must be side-by-side in a single, unbroken row.

In C, an array is a contiguous block of memory. "Contiguous" is a fancy way of saying there are no gaps. If you ask for five slots, the computer finds a space large enough for all five and marks it off just for you.

Calculating the Space

The total amount of memory an array consumes isn't just the number of elements; it is the number of elements multiplied by the size of the data type.

Think of it like this: if you book five rooms for single travelers, you need a certain amount of space. If you book five rooms for families of six, you need much more total space, even though you still only booked "five rooms."

In C, different types take up different amounts of "floor space" (measured in bytes):

  • An char usually takes 1 byte.
  • An int usually takes 4 bytes.

So, an array of 10 integers doesn't just take 10 "units" of memory—it takes 40 bytes (10 elements × 4 bytes each).

Seeing it in Code

You can use the sizeof operator in C to see this math in action. It tells you exactly how many bytes of memory a variable or type is using.

#include <stdio.h>

int main() {
    // An array of 5 integers
    int highScores[5];

    // On most systems, an int is 4 bytes.
    // 5 elements * 4 bytes = 20 bytes total.
    printf("Total bytes used by array: %zu\n", sizeof(highScores));

    return 0;
}

Why This Matters

Because arrays are one solid block, the computer can find any element instantly. If it knows where the first room is and knows every room is exactly 4 bytes wide, it can jump to the 100th room using simple multiplication. However, this also means you must decide the size upfront. You can't easily "tack on" an extra room later because the space next to your array might already be occupied by other data!

Key takeaway

An array's total memory footprint is its length multiplied by the byte-size of its data type, stored as one single, uninterrupted block.