No history yet

Arrays in C++

What is an Array?

An array is a way to store a collection of items under a single name. Think of it like a row of mailboxes. Each mailbox is a container, and the entire row is the array. Crucially, all items in an array must be of the same data type, and they are stored in a continuous block of memory, one right after the other.

This contiguous storage is the key characteristic of arrays. Because the computer knows where the array starts in memory and that each element is the same size, it can instantly calculate the location of any element. This makes accessing a specific item incredibly fast.

An array is a fixed-size sequence of elements, all of the same type, stored in contiguous memory locations.

Creating and Using Arrays

To declare an array in C++, you specify the type of its elements, a name for the array, and its size inside square brackets. The size must be a constant value known at compile time.

// Declares an array named 'scores' that can hold 5 integers.
// The elements are uninitialized and hold garbage values.
int scores[5];

It's best practice to initialize an array when you declare it. You can provide a list of initial values in curly braces. If you provide an initializer list, you can let the compiler determine the size of the array for you.

// Declare and initialize an array of 5 integers.
int scores[5] = {88, 92, 77, 95, 84};

// Let the compiler deduce the size from the list.
// This creates an identical array of size 5.
double temperatures[] = {68.5, 72.0, 75.4, 69.8};

Array elements are accessed using their index, which is their position in the sequence. C++ uses zero-based indexing, meaning the first element is at index 0, the second is at index 1, and so on. The last element is always at index size - 1.

// Access the third element (index 2)
int thirdScore = scores[2]; // thirdScore is now 77

// Modify the first element (index 0)
scores[0] = 90; // The array is now {90, 92, 77, 95, 84}

Iterating Over Arrays

A common task is to perform an operation on every element in an array. This is called iteration or traversal. A for loop is a natural fit for this job.

To iterate through an array, you can use a loop that counts from the first index (0) up to the last index (size - 1).

#include <iostream>

int main() {
    int scores[] = {90, 92, 77, 95, 84};
    // The array has 5 elements, so valid indices are 0, 1, 2, 3, 4.
    
    // Standard for loop
    for (int i = 0; i < 5; ++i) {
        std::cout << "Element at index " << i << ": " << scores[i] << std::endl;
    }
    
    return 0;
}

Modern C++ offers a simpler syntax for iteration: the range-based for loop. This loop automatically visits each element in the array from beginning to end without needing to manage an index variable. This is often safer and more readable.

#include <iostream>

int main() {
    int scores[] = {90, 92, 77, 95, 84};
    
    // Range-based for loop
    // 'score' will hold a copy of each element in 'scores', one by one.
    for (int score : scores) {
        std::cout << score << " ";
    }
    // Output: 90 92 77 95 84
    
    return 0;
}

Key Limitations

While powerful, C-style arrays have significant limitations you must be aware of. Understanding these trade-offs helps you decide when to use an array versus a more flexible container.

  1. Fixed Size: Once an array is declared, its size cannot be changed. You can't add or remove elements to make it grow or shrink. The size is fixed at compile time.
  1. No Bounds Checking: C++ does not automatically check if the index you are using is valid. If you have an array of size 5 and try to access scores[10], the program won't stop you. It will simply access a piece of memory outside the array's bounds. This leads to undefined behavior, which can cause unpredictable crashes, data corruption, and security vulnerabilities. It's one of the most common sources of bugs in C and C++ programs.
int numbers[3] = {10, 20, 30};

// DANGER: Accessing an out-of-bounds index!
// This compiles, but its behavior is undefined.
// It might print a garbage value, or it might crash the program.
numbers[3] = 40; 
  1. Array Decay: In many contexts, an array's name

decays

verb

The process where an array expression is implicitly converted into a pointer to its first element.

into a pointer to its first element. This means that if you pass an array to a function, the function only receives a pointer, not the entire array. It loses all information about the array's size.

These limitations are why C++ provides more advanced containers in its Standard Library, such as std::vector and std::array, which we will explore later. They build upon the core concept of arrays but add safety and flexibility.

Quiz Questions 1/6

What is the most defining characteristic of how a standard C-style array stores its elements?

Quiz Questions 2/6

If you declare an array as double readings[25];, what is the index of the very last element?