C++ Arrays: Contiguous Memory Layout, 2D Matrices & Safety Rules

An Array is a fixed-size, sequential collection of elements of identical data type stored in contiguous (unbroken) memory locations. Because memory is contiguous, any element can be accessed in constant time $O(1)$ via its index offset.

1D Array Declaration & Traversal

#include <iostream>

int main() {
    // 5 integers stored contiguously on the Stack
    int marks[5] = {85, 92, 78, 65, 95};

    int sum = 0;
    for (int i = 0; i < 5; ++i) {
        sum += marks[i];
    }

    double average = static_cast<double>(sum) / 5;
    std::cout << "Class Average: " << average << "\n";
    return 0;
}

2D Matrix Processing (Row-Major Order)

#include <iostream>

int main() {
    // 3 rows x 3 columns Matrix
    int matrix[3][3] = {
        {1, 2, 3},
        {4, 5, 6},
        {7, 8, 9}
    };

    std::cout << "Matrix Diagonal Elements: ";
    for (int i = 0; i < 3; ++i) {
        std::cout << matrix[i][i] << " ";
    }
    // Output: 1 5 9
    std::cout << "\n";
    return 0;
}

Frequently Asked Questions (FAQ) - Student & Interview Review

Q1. How are 2D arrays stored in physical computer memory in C++?

C++ stores multi-dimensional arrays in Row-Major Order. All elements of row 0 are stored in contiguous memory addresses, immediately followed by row 1, row 2, and so on.

Q2. Does C++ perform array bounds checking by default?

No! Raw C-style arrays (e.g. int arr[5]) do NOT perform runtime bounds checking. Accessing arr[10] causes Undefined Behavior (UB), which can silently corrupt memory or crash the program. Use std::vector or std::array with .at() for bounds checking.

Explore Related C++ Tutorials & Next Steps

Boost your C++ proficiency by studying these closely connected core modules:

Modern std::array

Safe, fixed-size container replacing raw C arrays.

Pointers and Arrays

Understanding array decay into raw pointers.

C++ std::vector

Dynamic arrays that resize automatically.

Share Share on Facebook Share on Twitter Share on LinkedIn Pin on Pinterest Share on Stumbleupon Share on Tumblr Share on Reddit Share on Diggit

You may also like this!