Arrays
Overview
If you need to store the scores of 1,000 players in a video game, creating 1,000 individual variables (int p1, p2...) is impossible. An Array solves this by allocating a single, massive block of contiguous (side-by-side) memory to store multiple elements of the exact same data type.
Because the memory is contiguous, the CPU can instantly jump to any element mathematically by calculating its 'offset' from the start of the array. This is why arrays offer blazing fast $O(1)$ random access time. However, classic C-style arrays are notorious for being structurally rigid; their size is permanently locked the moment they are created and cannot grow or shrink dynamically.
Syntax
// 1. Declaration and Initialization
// The size [5] is permanently locked!
int scores[5] = {10, 20, 30, 40, 50};
// 2. Auto-sizing based on initialization elements
int autoSized[] = {1, 2, 3}; // Size is exactly 3
// 3. Accessing Elements (Arrays are 0-Indexed!)
int firstScore = scores[0]; // 10
// 4. Modifying Elements
scores[4] = 99; // Changes 50 to 99Common Pitfalls
- Accessing out of bounds (Memory Corruption). If an array has 5 elements, its highest index is
4. If you try to read or writescores[5], C++ does NOT stop you! It blindly jumps to that memory address and corrupts whatever data belongs to another variable sitting there. - Arrays losing their size. In raw C++, arrays do not 'know' their own length. If you pass an array to a function, it strictly degrades (decays) into a raw memory pointer to its first element, completely forgetting how big it originally was.
Interview Questions
Array indices aren't just abstract numbers; they are mathematically literal memory 'offsets'. The address of the first element is exactly at the start of the array block (Offset of 0 memory blocks). The second element is offset by 1 block, etc. Starting at 0 eliminates a subtraction operation (index - 1), slightly speeding up CPU calculations for every single array access.
std::vector instead of raw C-style arrays?Raw arrays are fundamentally unsafe and rigid. They don't track their own size, don't perform bounds checking, and cannot dynamically resize. std::vector is a modern, dynamic array wrapper that automatically grows when full, perfectly manages its own memory size, and provides safety functions.
Real-World Example
Dynamically calculating the size of an array without hardcoding it.
#include <iostream>
int main() {
int scores[] = {85, 92, 78, 90, 88};
// Total size of array in bytes (5 * 4 = 20) divided by the size of one element (4)
// Equals 5 elements!
int numElements = sizeof(scores) / sizeof(scores[0]);
int sum = 0;
for (int i = 0; i < numElements; i++) {
sum += scores[i];
}
std::cout << "Average: " << (float)sum / numElements << "\n";
return 0;
}Check Your Knowledge
Test your understanding of Arrays with these quick questions.