C-Style Arrays
Declaring arrays
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
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
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:
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
int grid[3][4] = {}; // 3 rows, 4 columns
grid[1][2] = 7;
Arrays can't be assigned or compared
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 arrays | Modern fix |
|---|---|
| Lose size when passed | std::array, std::vector, std::span |
| No bounds checking | .at() |
| Can't copy/assign | std::array copies with = |
| Fixed size | std::vector grows |
Example
#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
*/