Skip to content
Tutorials Center
My learning

Topics

Lesson 36 of 171 ยท Arrays and Vectors

C-Style Arrays

Learn C-style arrays in C++ - declaring, initializing and indexing, why there is no bounds checking, how arrays decay to pointers, and when to use std::array instead.

So far every variable you've created holds one value. Real data comes in groups: twelve monthly totals, a hundred sensor readings, the squares of a game board. An array stores a fixed number of values of the same type side by side in memory, under one name, and lets you reach each one by its position.

C++ inherited its built-in arrays from C, so they are often called C-style arrays or raw arrays. They are fast and simple, but they have rough edges: they don't know their own size once you pass them around, they can't be copied with =, and reading past the end is silently undefined behavior. This lesson teaches them properly, because you'll meet them in every codebase and they explain how the safer containers work. It ends with why modern code usually prefers std::array and std::vector.

Declaring an array

An array declaration gives the element type, the name, and the number of elements in square brackets:

C++
int monthly_sales[12];        // 12 ints
double readings[100];         // 100 doubles
char initials[3];             // 3 chars

The size is part of the array's type: monthly_sales has type int[12], which is a different type from int[11]. That's why the size must be a constant expression, a value the compiler knows while compiling: a literal, a constexpr variable or a const integer initialized from a constant.

C++
constexpr int days_in_week = 7;
int steps[days_in_week];      // fine: known at compile time

int n = 7;
int other[n];                 // NOT standard C++: n is a runtime value

The last line compiles with GCC and Clang because they support C's variable-length arrays as an extension, but it is not valid C++, MSVC rejects it, and a large n can overflow the stack. Compile with -pedantic-errors to catch it. When the size is only known at runtime, use std::vector.

Initializing an array

A local array without an initializer is filled with indeterminate values, whatever bytes happened to be in that memory. Reading them is undefined behavior, exactly like an uninitialized int (see Variables). So always initialize:

C++
int a[5] = {10, 20, 30, 40, 50};   // all five given
int b[5] = {10, 20};               // the rest become 0: {10, 20, 0, 0, 0}
int c[5]{};                        // all zero
int d[] = {1, 2, 3};               // size deduced from the list: int[3]
int e[2] = {1, 2, 3};              // error: too many initializers

The rule behind b and c is worth remembering: in a brace list, any elements you don't mention are value-initialized, which means zero for numbers. int c[5]{} is the idiomatic way to get an array of zeros. The = is optional with braces: int a[5]{10, 20, 30, 40, 50} is the same.

C++ Declaring and initializing arrays

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

partial prints 9 8 0 0 0 0, the size of vowels is deduced as 5, and primes occupies 20 bytes: five 4-byte ints with no extra bookkeeping. An array is nothing but its elements, stored contiguously (one right after the other).

Arrays declared at namespace scope (globals) or with static are zero-initialized automatically, but don't rely on that for locals.

Indexing: zero to size minus one

You reach an element with the subscript operator []. Indexes start at 0, so an array of N elements has valid indexes 0 to N - 1:

TEXT
int scores[5] = {72, 88, 95, 60, 81};

index:     0    1    2    3    4
         +----+----+----+----+----+
scores:  | 72 | 88 | 95 | 60 | 81 |
         +----+----+----+----+----+

scores[2] is 95. You can read and assign through an index, and the index can be any integer expression. Two loops cover almost every need: the range-based for when you want every element, and an index loop when you need the position too.

C++ Working through an array

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

std::size(scores) (from <iterator>, C++17) gives the number of elements as a std::size_t. Using it instead of repeating the literal 5 means the loop stays correct if you add a sixth score. The int& in the last loop is a reference, so each score is an element rather than a copy; for Loops explains by-value vs by-reference loops in detail.

No bounds checking

Here is the most important fact about C-style arrays: the [] operator does not check the index. Writing scores[5] or scores[-1] on a five-element array doesn't throw an exception or stop the program. It computes an address outside the array and reads or writes whatever is there. That is undefined behavior: the program might print garbage, crash, appear to work, or overwrite another variable and fail much later somewhere unrelated.

C++
int scores[5] = {72, 88, 95, 60, 81};
scores[5] = 100;              // UB: one past the end
for (int i = 0; i <= 5; ++i)  // UB: the classic off-by-one, <= should be <
    std::println("{}", scores[i]);

Out-of-bounds writes are behind a huge share of real security vulnerabilities ("buffer overflows"). The compiler warns only when it can prove the index is wrong at compile time, which is rare in real code.

Your defenses:

  • Loop with i < std::size(arr) (never <=), or better, use range-based for and have no index at all.
  • Validate indexes that come from outside (input, files, network) before using them, as in the next example.
  • Use std::array::at() or std::vector::at(), which check and throw std::out_of_range.
  • Run tests with sanitizers. -fsanitize=address reports the exact line of an out-of-bounds access (Undefined Behavior and Memory Safety).
C++ Checking an index from input

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Indexes 3 and 0 are accepted; 7 and -1 are rejected before they reach []. The check uses a signed int on purpose: if index were unsigned, -1 would turn into a huge number (see Integer Types), which also fails the test, but the message would be confusing.

Arrays can't be assigned or compared

Arrays are not "values" the way int or std::string are. You can't assign one array to another, and you can't return an array from a function:

C++
int a[3] = {1, 2, 3};
int b[3];
b = a;               // error: invalid array assignment
int c[3] = a;        // error: an array can't be initialized from another array

Comparing with == is worse, because it compiles: a == b compares the addresses of the two arrays, not their contents, so it is false for two different arrays even when every element matches. C++20 deprecated this comparison and GCC warns about it, but don't count on noticing a warning.

To copy or compare contents, use the standard algorithms:

C++ Copying and comparing contents

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The last line shows that std::println can format a whole array (C++23 range formatting). Sorting, searching and copying all work on raw arrays because they are contiguous ranges; std::array simply makes = and == do the obvious thing.

Array decay: arrays turn into pointers

In almost every expression, an array is automatically converted to a pointer to its first element. This is called array-to-pointer decay. It happens when you pass an array to a function, when you assign it to a pointer, and in arithmetic. It does not happen with sizeof, &arr, std::size or when binding a reference to the array.

Decay has one painful consequence: a function parameter that looks like an array is really a pointer.

C++
void print_all(int values[]);      // exactly the same as:
void print_all(int* values);       // the array size is lost
void print_all(int values[10]);    // still just int*: the 10 is ignored!

So inside the function, sizeof(values) is the size of a pointer (8 bytes on a 64-bit system), and std::size(values) doesn't compile. The traditional C solution is to pass the length as a second argument:

C++ Arrays decay when passed to functions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

In main, sizeof(temps) is 24 (six ints). The pointer first is 8 bytes no matter how big the array is. The show template receives the array by reference (const int (&values)[N], read "values is a reference to an array of N const ints"), so no decay happens and the compiler deduces N for you. Templates come later in Function Templates; the point here is that pointer + length is easy to get wrong, and C++20's std::span bundles the two safely.

You'll see the full story of pointers and arrays in Pointers and Arrays.

The sizeof trick and why std::size is better

Older code counts elements with sizeof(arr) / sizeof(arr[0]), often wrapped in a macro. It works on a real array but silently gives a wrong answer on a decayed pointer (8 / 4 = 2 on a typical 64-bit system). std::size gives the same answer for arrays and refuses to compile for pointers, so mistakes become compile errors. Prefer it.

Arrays of characters

A char array can be initialized from a string literal, which copies the characters and adds a terminating null character '\0':

C++
char greeting[] = "hi";    // {'h', 'i', '\0'}: 3 elements, not 2

This is how C represents strings, and it has its own lesson: C-Style Strings and Character Arrays. In C++ code, use std::string unless you have a specific reason not to.

Why modern C++ prefers std::array and std::vector

C-style arrays are a low-level building block. Everything they do, the standard containers do at least as well, without the traps:

Problem with T[N] std::array<T, N> std::vector<T>
Size lost when passed to a function Size is part of the type and kept Carries its size
Can't copy with =, == compares addresses = copies, == compares contents Same
Can't be returned from a function Can be returned Can be returned
No checked access at() throws on a bad index at() throws on a bad index
Size fixed at compile time Fixed (same as C array) Grows and shrinks at runtime
Overhead None: same memory layout A small header plus heap storage

std::array costs nothing extra at runtime, so for a fixed-size collection there's little reason to write a raw array in new code. You'll still use raw arrays occasionally: when calling C libraries, for string literals, and in low-level code. Knowing how they decay and why they aren't bounds-checked will make those situations safe.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. int values[6] = {4, 2}; What is values[5]?

    In a brace initializer, elements you don't list are value-initialized, which is 0 for int. Only an array with no initializer at all holds indeterminate values.
  2. 2. What happens when you write arr[10] = 1; on an int arr[10];?

    C-style arrays have no bounds checking. Index 10 is one past the end, so the write lands outside the array, which is undefined behavior.
  3. 3. Inside void f(int data[20]), what is sizeof(data) on a typical 64-bit system?

    An array parameter is adjusted to a pointer, so data is an int* and sizeof gives the pointer size, 8 bytes. The 20 in the declaration is ignored.
  4. 4. int a[3] = {1, 2, 3}; int b[3] = {1, 2, 3}; Why should you not write a == b to compare them?

    Both arrays decay to pointers, so == compares addresses. C++20 deprecates this. Use std::ranges::equal(a, b), or std::array, whose == compares contents.
  5. 5. Why is std::size(arr) safer than sizeof(arr) / sizeof(arr[0])?

    The sizeof division silently returns a wrong number for a pointer. std::size only accepts real arrays and containers, so the mistake becomes a compile error.

Summary

  • A C-style array T name[N] holds N elements of type T contiguously; N must be a compile-time constant and is part of the type.
  • Always initialize: {...} fills unlisted elements with zero, {} zeroes everything, int d[] = {...} deduces the size.
  • Indexes run from 0 to N - 1. [] is not bounds-checked, so out-of-range access is undefined behavior. Use std::size, i < size loops, range-based for and input validation.
  • Arrays can't be assigned or returned, and == compares addresses; use std::ranges::copy and std::ranges::equal.
  • Arrays decay to a pointer to their first element, so array parameters lose their size. Pass a length, take the array by reference, or use std::span.
  • Prefer std::array for fixed sizes and std::vector for dynamic sizes in new code.

Next: std::array, the fixed-size array that knows its size, copies with = and checks indexes with at(), at zero cost.