C++ Arrays
An array is a fixed-size collection of elements of the same type stored contiguously in memory, declared as `type name[size];`. Elements are accessed by a zero-based index using `[]`.
Raw C-style arrays don't know their own size and don't bounds-check, so modern C++ often prefers `std::array` or `std::vector` for safety, but plain arrays remain common in competitive programming for speed.
Declaring and accessing
`int nums[5] = {1,2,3,4,5};` creates a fixed array; `nums[0]` is the first element, `nums[4]` the last. Accessing out of bounds is undefined behaviour.
Array size
`sizeof(arr) / sizeof(arr[0])` gives the element count for a raw array โ this trick fails once the array decays to a pointer (e.g. passed to a function).
int nums[3] = {10, 20, 30};
std::cout << nums[1];20Index 1 accesses the second element.
int arr[4] = {1,2,3,4};
int n = sizeof(arr) / sizeof(arr[0]);
std::cout << n;4Computes the number of elements in the array.
Key points
- Arrays have a fixed size set at declaration.
- Indexing is zero-based and unchecked.
- sizeof trick gives element count for raw arrays.
- std::array/std::vector are safer modern alternatives.
