C++
Module 9: ArraysBeginner45 min read

1D & 2D Arrays, Memory Layout & Array Algorithms

Understand contiguous array memory layout, 1D/2D arrays, array decay when passing to functions, reversal, rotation, and std::array.

Key Takeaways & Core Concepts
  • random access via *(arr + i). 2D arrays int mat[R][C] are stored in row-major order in memory (row 0 followed by row 1), making row-wise traversal cache-friendly.
  • it to int*, losing its size. Prefer std::array<int, N> (fixed size, knows .size(), supports .at() bounds checking) or std::vector<int> (dynamic size).

1. Contiguous Memory Layout & Row-Major 2D Arrays

Arrays store elements in contiguous memory, giving O(1) random access via *(arr + i). 2D arrays int mat[R][C] are stored in row-major order in memory (row 0 followed by row 1), making row-wise traversal cache-friendly.

1. std::array & In-Place Array Rotation
1#include <iostream>
2#include <array>
3#include <algorithm>
4
5int main() {
6 std::array<int, 5> arr = {1, 2, 3, 4, 5};
7 std::rotate(arr.begin(), arr.begin() + 2, arr.end()); // Left rotate by 2
8 for (int x : arr) std::cout << x << " ";
9 return 0;
10}
Click code or "Edit Code" to edit
Interactive Code Block•Tab = 4 spaces•Ctrl + Enter = Run
10 lines
Note: Uses `std::array` with `std::rotate` for O(n) in-place rotation.

2. Array Decay & Modern `std::array` / `std::span`

Passing a C-array int arr[] to a function decays it to int*, losing its size. Prefer std::array<int, N> (fixed size, knows .size(), supports .at() bounds checking) or std::vector<int> (dynamic size).

3. Common Array Algorithms

Reversal, rotation, duplicate detection, searching, and sorting (std::sort).

Practice & AssessmentC++ Programming Tutorial

Test Your Understanding

Reinforce core concepts with interactive multiple-choice questions, live coding challenges, and top technical interview questions.

Your Current Score

0 / 0 correct(0 attempted)