Array Memory Layout
What you'll learn: You'll understand how arrays are physically stored in memory and how computers quickly find any element using simple math.
Why Arrays Are Fast
When you declare an array, the computer reserves a contiguous block of memory—meaning all elements sit side-by-side in a single unbroken line, like houses on a street with consecutive addresses. This is different from scattered storage where elements could be anywhere.
How Memory Addresses Work
Imagine memory as a numbered street where each "house" (memory location) has an address. If you declare int numbers[5], the computer:
- Finds space for 5 integers in a row
- Records the base address (the starting location)
- Knows each
inttakes a fixed amount of space (say, 4 bytes)
Calculating Element Positions
To access numbers[3], the computer doesn't search through the array. Instead, it calculates:
Address of numbers[3] = base_address + (3 × size_of_int)
If the base address is 1000 and each integer is 4 bytes:
numbers[0]→ address1000numbers[1]→ address1004numbers[2]→ address1008numbers[3]→ address1012
One multiplication and one addition—instant access! This is why array indexing is so fast and why it's called "random access."
The Memory Layout Guarantee
Because arrays are contiguous, iterating through them is also fast. The computer can predict where the next element lives, making efficient use of memory caching.
Key Takeaway: Arrays store elements in consecutive memory locations, allowing instant access to any element through a simple calculation: base_address + (index × element_size).