Skillversitas

Arrays in C++

An array is a collection of variables of the same data type stored sequentially in memory. Each element is accessed via an index starting from 0. Arrays make it easy to manage large amounts of data without declaring one variable at a time.

In C++, there are two main types of arrays: C-style arrays (traditional arrays) and std::array (a modern container from C++11). Each has its own advantages. C-style arrays are lighter but less safe, while std::array provides extra features such as .size() and integration with the STL.

Static arrays have a fixed size at compile time. Elements that are not initialized will contain garbage values (indeterminate values). For dynamic arrays, we use new or std::vector.

Declaration and Initialization

Arrays are declared using the format type name[number of elements]. Initialization can be done at declaration time or later.

Multidimensional Arrays

Arrays can have more than one dimension. 2D arrays are often used to represent matrices or tables. Format: type name[rows][columns]. 3D and higher-dimensional arrays are rarely used but are available.

Arrays and Pointers

Arrays in C++ have a close relationship with pointers. An array name acts as a pointer to the first element. When an array is passed to a function, what is passed is the address of the first element (array decay to pointer), so the function does not know the array's size.

Code Example

#include <iostream>
#include <array>

using namespace std;

void printArray(int arr[], int size) {
    for (int i = 0; i < size; i++) {
        cout << arr[i] << " ";
    }
    cout << endl;
}

void print2D(int arr[3][3]) {
    for (int i = 0; i < 3; i++) {
        for (int j = 0; j < 3; j++) {
            cout << arr[i][j] << " ";
        }
        cout << endl;
    }
}

int main() {
    // Declaration and initialization of a C-style array
    int numbers[5] = {10, 20, 30, 40, 50};
    int letters[] = {'A', 'B', 'C'}; // size automatically 3
    int empty[5] = {}; // all elements = 0

    // Accessing elements
    cout << "First element: " << numbers[0] << endl;
    cout << "Third element: " << numbers[2] << endl;

    // Modifying an element
    numbers[1] = 25;
    cout << "After modification: ";
    printArray(numbers, 5);

    // Array size
    int totalElements = sizeof(numbers) / sizeof(numbers[0]);
    cout << "Number of elements: " << totalElements << endl;

    // 2D array
    int matrix[3][3] = {
        {1, 2, 3},
        {4, 5, 6},
        {7, 8, 9}
    };
    cout << "\n3x3 matrix:" << endl;
    print2D(matrix);

    // 3D array
    int box[2][3][2] = {
        {{1, 2}, {3, 4}, {5, 6}},
        {{7, 8}, {9, 10}, {11, 12}}
    };
    cout << "\nElement box[1][2][0]: " << box[1][2][0] << endl;

    // Looping over an array with a range-based for
    cout << "\nContents of letters: ";
    for (int h : letters) {
        cout << h << " ";
    }
    cout << endl;

    // std::array (C++11)
    array<int, 5> modern = {100, 200, 300, 400, 500};
    cout << "\nstd::array size: " << modern.size() << endl;
    for (const auto& val : modern) {
        cout << val << " ";
    }
    cout << endl;

    // Use case: computing the average of student grades
    double scores[5] = {85.5, 90.0, 78.5, 92.0, 88.5};
    double total = 0;
    for (int i = 0; i < 5; i++) {
        total += scores[i];
    }
    double average = total / 5;
    cout << "\nAverage score: " << average << endl;

    return 0;
}

Code Explanation

  • int numbers[5] = {10, 20, 30, 40, 50}; — Declares a 5-element array with direct initialization. The braces {} contain the initial values.
  • int letters[] = {'A', 'B', 'C'}; — The array size is determined automatically based on the number of elements inside the curly braces, which is 3.
  • int empty[5] = {}; — All elements are initialized to 0. This is a safe way to avoid garbage values.
  • numbers[0] — Accesses the first element. Indices start from 0, so the last index for an array of size 5 is 4.
  • numbers[1] = 25; — Changes the value of the second element from 20 to 25.
  • sizeof(numbers) / sizeof(numbers[0]) — Counts the number of elements by dividing the array's total bytes by the bytes of one element. This only works in the same scope as the array's declaration.
  • printArray(int arr[], int size) — A function that receives an array as a parameter. It needs a separate size parameter because the array decays to a pointer when passed to a function.
  • int matrix[3][3] — A 2D array with 3 rows and 3 columns. Accessed with matrix[row][column].
  • for (int h : letters) — A range-based for loop (C++11). Automatically iterates through each element of the array.
  • array<int, 5> modern — A std::array from the <array> header. Safer than a C-style array because it has a .size() method and supports iterators.
  • sizeof(box[1][2][0]) — A 3D array is accessed with three indices. The box contains 2 blocks, each with 3 rows, each with 2 columns.
  • Average calculation — A loop that sums all elements and then divides by the number of elements. This is a very common use of arrays.

Everyday Use Cases

Imagine you are a teacher who needs to manage the grades of 30 students in one class. Instead of creating 30 separate variables (score1, score2, ..., score30), just use an array double scores[30]. You can compute the average, find the highest grade, and find the lowest grade with a single loop.

Other practical examples:
- Shopping list: string shopping[] = {"rice", "sugar", "oil"}; — Stores a list of shopping items.
- Game grid: A 2D array can represent a game map, where each cell holds information about the state of that location.
- Temperature sensor: An array stores temperature readings throughout the day to be analyzed later.

Conclusion

Arrays are a fundamental data structure in C++ that store sequential elements of the same type. C-style arrays are easy to use but require care regarding size and index bounds. std::array (C++11) is safer and more modern. Multidimensional arrays are useful for data shaped like tables or grids. Always make sure indices do not go out of bounds (out-of-bound) to avoid undefined behavior.