C++ ยท Chapter 20 of 49

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).

Example 1 (cpp)
int nums[3] = {10, 20, 30};
std::cout << nums[1];
Output
20

Index 1 accesses the second element.

Example 2 (cpp)
int arr[4] = {1,2,3,4};
int n = sizeof(arr) / sizeof(arr[0]);
std::cout << n;
Output
4

Computes 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.
๐Ÿ’ก Note: Out-of-bounds array access does not throw an error in C++ โ€” it silently corrupts memory, so be careful.

๐Ÿ“ Quick Quiz

1. What is the index of the last element in a 5-element array?

2. What happens on out-of-bounds array access?

3. A safer, resizable alternative to raw arrays is: