How Array Works in Memory: Explanation and Examples
An
array stores elements in a continuous block of memory, where each element is placed one after another. This allows quick access to any element using its index by calculating its memory address based on the starting point and element size.Syntax
An array is declared by specifying the type of elements and the number of elements it will hold. The syntax varies by language but generally looks like this:
- Type: The kind of data stored (e.g., integer, float).
- Size: Number of elements the array can hold.
- Index: Position of an element, starting at 0.
Each element is stored in memory one after another without gaps.
c
int arr[5];
Example
This example shows how an array of integers is stored and accessed in memory. The array arr holds 5 integers, and accessing arr[2] retrieves the third element by calculating its memory address.
c
#include <stdio.h> int main() { int arr[5] = {10, 20, 30, 40, 50}; printf("Element at index 2: %d\n", arr[2]); return 0; }
Output
Element at index 2: 30
Common Pitfalls
Common mistakes when working with arrays in memory include:
- Accessing elements outside the array bounds, which can cause errors or unexpected behavior.
- Assuming arrays can grow dynamically; fixed-size arrays have a set size in memory.
- Confusing the array name with a pointer without understanding memory layout.
Always ensure indexes are within valid range and understand the fixed size nature of arrays.
c
int arr[3] = {1, 2, 3}; // Wrong: Accessing out of bounds int x = arr[5]; // Undefined behavior // Correct: Access within bounds int y = arr[2];
Quick Reference
| Concept | Description |
|---|---|
| Continuous Memory | Array elements are stored one after another in memory. |
| Indexing | Access elements by calculating address: base_address + index * element_size. |
| Fixed Size | Array size is fixed at declaration and cannot change. |
| Fast Access | Direct memory calculation allows quick element retrieval. |
| Out of Bounds | Accessing invalid indexes causes errors or undefined behavior. |
Key Takeaways
Arrays store elements in a continuous block of memory for fast access.
Each element's memory address is calculated using the base address plus index times element size.
Array size is fixed and must be known at declaration time.
Accessing elements outside the array bounds leads to errors or undefined behavior.
Understanding memory layout helps avoid common mistakes with arrays.