While C-style arrays have their uses, they come with several pitfalls and limitations. Modern C++ offers some powerful alternatives:
std::array
The primary use for std::array
is for fixed-size arrays. They have the following properties:
.at()
.#include <array>
std::array<int, 3> arr = {1, 2, 3};
std::vector
 When we need an array whose size needs to change at run time, std::vector
is the typical choice. They have the following properties:
#include <vector>
std::vector<int> vec = {1, 2, 3};
vec.push_back(4);
std::string
 (for strings)When we have a text string (a collection of characters), the standard library’s std::string
type is ideally suited.
#include <string>
std::string str = "Hello";
std::span
 (for array views, since C++20)When we want a general view of an array that does not own the underlying collection, we can use a std::span
. They have the following properties:
#include <span>
void func(std::span<int> sp) {
// Work with sp
}
int main() {
int arr[] = {1, 2, 3};
func(arr);
}
These alternatives provide safer, more flexible, and more expressive ways to work with collections of objects in C++. They integrate well with the rest of the Standard Library and support modern C++Â idioms.
However, C-style arrays still have their place, particularly when interacting with C code or in low-level programming. Understanding both C-style arrays and their modern alternatives is important for writing effective C++Â code.
Answers to questions are automatically generated and may not have been reviewed.
A detailed guide to working with classic C-style arrays within C++, and why we should avoid them where possible