In legacy C, passing an array to a function causes it to decay into a raw pointer, completely losing its size information. Modern C++11 solved this design flaw by introducing std::array<T, N> in the <array> header.
#include <iostream>
#include <array>
#include <algorithm> // For std::sort
int main() {
// Fixed size 5 on Stack, Knows its own size!
std::array<int, 5> data = {40, 10, 50, 20, 30};
std::cout << "Array size: " << data.size() << "\n";
// STL Algorithm compatibility
std::sort(data.begin(), data.end());
std::cout << "Sorted: ";
for (const auto& num : data) {
std::cout << num << " ";
}
// Output: 10 20 30 40 50
std::cout << "\n";
// Safe bounds checking
try {
int invalid = data.at(10); // Out of bounds!
} catch (const std::out_of_range& e) {
std::cout << "Caught safe exception: " << e.what() << "\n";
}
return 0;
}
Boost your C++ proficiency by studying these closely connected core modules:
Understanding legacy arrays and array decay.
When dynamic resizing is needed instead of fixed size.
Using begin() and end() iterators with std::array.