C++ · Module 6 · Lesson 11 min read

C-Style Arrays

Declaring arrays

scss
int marks[5];                       // 5 ints, uninitialized (garbage!)
int marks[5] = { 80, 75, 92 };      // rest become 0
int marks[] = { 80, 75, 92 };       // size deduced: 3
int zeros[100] = {};                // all zero ✅
  • Size must be a compile-time constant
  • Elements are stored contiguously (next to each other) in memory
  • Indexes go from 0 to size − 1

Accessing elements

ini
marks[0] = 90;
std::cout << marks[2];

⚠️ No bounds checking: marks[10] on a 5-element array is undefined behaviour — it may crash, or silently corrupt other data.

Size of an array

c
std::size(marks)                         // C++17 ✅ (<iterator>)
sizeof(marks) / sizeof(marks[0])         // C way

Arrays decay to pointers ⚠️

When passed to a function, an array becomes a pointer to its first element and loses its size:

arduino
void print(int arr[], int n);   // you must pass the size separately

Inside the function, sizeof(arr) is the size of a pointer (8), not the array!

2D arrays

CSS
int grid[3][4] = {};    // 3 rows, 4 columns
grid[1][2] = 7;

Arrays can't be assigned or compared

less
int a[3] = {1,2,3}, b[3];
b = a;        // ❌ error
a == b        // compares addresses, not contents!

Why modern C++ prefers alternatives

Problem with C arraysModern fix
Lose size when passedstd::array, std::vector, std::span
No bounds checking.at()
Can't copy/assignstd::array copies with =
Fixed sizestd::vector grows

Example

C++
#include <iostream>
#include <iterator>

double average(const int arr[], int n) {          // arr is really a pointer here
    int sum = 0;
    for (int i = 0; i < n; ++i) sum += arr[i];
    return static_cast<double>(sum) / n;
}

int main() {
    int marks[] = { 80, 75, 92, 68, 88 };
    int counts[5] = { 3, 1 };                       // remaining elements become 0

    std::cout << "marks has " << std::size(marks) << " elements, "
              << sizeof(marks) << " bytes\n";
    std::cout << "counts:";
    for (int c : counts) std::cout << ' ' << c;
    std::cout << '\n';

    marks[3] = 70;                                   // modify an element
    int best = marks[0];
    for (int m : marks) if (m > best) best = m;
    std::cout << "best = " << best << ", average = " << average(marks, std::size(marks)) << '\n';

    // 2D array: 3 days x 4 expense categories
    int week[3][4] = { { 500, 0, 120, 0 }, { 450, 15000, 80, 200 }, { 600, 0, 100, 0 } };
    for (int day = 0; day < 3; ++day) {
        int total = 0;
        for (int cat = 0; cat < 4; ++cat) total += week[day][cat];
        std::cout << "Day " << day + 1 << " total: " << total << '\n';
    }
    // marks[5] = 1;   // out of bounds: undefined behaviour, no error message!
    return 0;
}

/* Output:
marks has 5 elements, 20 bytes
counts: 3 1 0 0 0
best = 92, average = 81
Day 1 total: 620
Day 2 total: 15730
Day 3 total: 700
*/