C++ inherited arrays from C where they are used virtually everywhere. C++ provides abstractions that are easier to use and less error-prone (std::vector<T>
since C++98 and std::array<T, n>
since C++11), so the need for arrays does not arise quite as often as it does in C. However, when you read legacy code or interact with a library written in C, you should have a firm grasp on how arrays work.
This FAQ is split into five parts:
- arrays on the type level and accessing elements
- array creation and initialization
- assignment and parameter passing
- multidimensional arrays and arrays of pointers
- common pitfalls when using arrays
If you feel something important is missing in this FAQ, write an answer and link it here as an additional part.
In the following text, “array” means “C array”, not the class template std::array
. Basic knowledge of the C declarator syntax is assumed. Note that the manual usage of new
and delete
as demonstrated below is extremely dangerous in the face of exceptions, but that is the topic of another FAQ.
(Note: This is meant to be an entry to Stack Overflow’s C++ FAQ. If you want to critique the idea of providing an FAQ in this form, then the posting on meta that started all this would be the place to do that. s to that question are monitored in the C++ chatroom, where the FAQ idea started out in the first place, so your answer is very likely to get read by those who came up with the idea.)