C++: Arrays

Declare and use one-dimensional, multi-dimensional, and character arrays, pass them to functions, and work with C-style string functions.

Array Declaration and Initialization

An array stores a fixed number of elements of the same type in contiguous memory. The size must be a compile-time constant when declared on the stack. Elements can be initialized in the declaration using a brace list.

Array Declaration

Declare an array with its type, name, and size in square brackets, the size is fixed for the lifetime of the array.

  • Syntax: type name[size];
  • Partial initialization: int arr[5] = {1, 2};, remaining elements are zero-initialized
  • Full initialization: int arr[] = {1, 2, 3};, compiler deduces size as 3
  • Uninitialized local arrays hold garbage values, always initialize

Array Declaration and Initialization

C++

A fully initialized array and a zero-initialized array.

Accessing Array Elements

Array elements are accessed with the index operator []. Indices start at 0 and go up to size - 1. Accessing outside this range is undefined behavior, C++ does not perform bounds checking.

Array Indexing

Out-of-bounds access is undefined behavior, the program may silently corrupt memory or crash. Always stay within 0 to size-1.

  • First element: arr[0], last element: arr[size - 1]
  • Read: int x = arr[2];
  • Write: arr[2] = 99;
  • C++ does not check bounds, accessing arr[10] on a 5-element array is a bug, not an error

Accessing and Modifying Elements

C++

Read the first and last elements, then overwrite the middle one.

Array Size Using sizeof

Since C-style arrays do not carry their size, use sizeof(arr) / sizeof(arr[0]) to compute the element count at compile time without hard-coding the number.

sizeof for Array Size

This idiom only works when arr is the actual array, once an array decays to a pointer (e.g. inside a function), sizeof gives the pointer size, not the array size.

  • sizeof(arr) gives total bytes occupied by the array
  • sizeof(arr[0]) gives bytes per element
  • Element count: sizeof(arr) / sizeof(arr[0])
  • Prefer std::size(arr) (C++17) or a constant for clarity

Array Size with sizeof

C++

Compute the element count without hard-coding 5.

Iterating Through Arrays

The most common way to visit every element is a for loop with an index, or a range-based for loop (C++11) when you do not need the index.

Iterating Arrays

Use an index-based for loop when you need the position; use range-based for when you only need the value.

  • Index-based: for (int i = 0; i < size; i++): use when index matters
  • Range-based: for (int x : arr): cleaner, but no index available
  • Use const auto& in range-based for to avoid copying and prevent modification

Two Ways to Iterate

C++

Both loops produce the same output, choose based on whether you need the index.

2D Arrays

A 2D array is an array of arrays, think of it as a grid with rows and columns. It is declared with two size specifiers and accessed with two indices: arr[row][col].

2D Arrays

Memory is laid out row by row (row-major order), arr[0] is the entire first row stored contiguously.

  • Syntax: type name[rows][cols];
  • Initialize with nested braces: {{1,2},{3,4},{5,6}}
  • Access element at row r, column c: arr[r][c]
  • Total elements: rows multiplied by cols

2D Array: 3x3 Grid

C++

Declare, initialize, and print a 3x3 integer grid.

3D Arrays

A 3D array adds a third dimension, think of it as multiple 2D grids stacked together. Access uses three indices: arr[layer][row][col].

3D Arrays

3D arrays are rare in practice, only use them when the data is genuinely three-dimensional (e.g. voxel grids, RGB image batches).

  • Syntax: type name[depth][rows][cols];
  • Access: arr[d][r][c]
  • Total elements: depth multiplied by rows multiplied by cols
  • For most use cases, a flat 1D array with manual index arithmetic is more flexible

3D Array Access

C++

Three indices select layer, row, and column.

Passing Arrays to Functions

When you pass an array to a function, it decays to a pointer to its first element. No copy is made. Because the function receives a pointer, you must also pass the size separately, the function cannot compute it with sizeof from inside.

Array Decay to Pointer

An array passed to a function is just a pointer, changes made inside the function affect the original array, and sizeof inside the function gives the pointer size, not the array size.

  • Syntax: void func(int arr[], int size) or void func(int* arr, int size)
  • Both notations are identical, the parameter is a pointer
  • Always pass the size as a separate argument
  • Modifications inside the function change the original array

Passing an Array to a Function

C++

Pass the array and its size, the function cannot determine size on its own.

Returning Arrays from Functions

C++ does not allow returning a local array by value directly, the array is destroyed when the function returns. The safe alternatives are: use a static array, pass an output array as a parameter, or use std::vector (preferred in modern C++).

Returning Arrays

Never return a pointer to a local array, the local memory is invalid after the function returns. Use static, an output parameter, or std::vector instead.

  • Option 1: pass an output array as a parameter (caller owns the memory)
  • Option 2: return a static array (only one copy exists, not thread-safe)
  • Option 3: return std::vector<int>, safe, clean, and preferred in modern C++

Output Array as Parameter

C++

The caller allocates the array; the function fills it in.

C-style Strings

A C-style string is a char array terminated by a null character '\0'. All C string functions from <cstring> rely on this null terminator to know where the string ends.

C-style Strings (char arrays)

Declare the array one byte larger than the intended string to leave room for the null terminator.

  • char name[6] = "Hello"; stores H,e,l,l,o,\0, 6 bytes total
  • String literal assignment automatically appends \0
  • Without \0, string functions will read past the end of the array (undefined behavior)
  • In modern C++, prefer std::string, C-style strings exist for legacy and embedded use

C-style String

C++

A char array with a null terminator printed directly with cout.

String Input and Output

cout prints a char array until it hits '\0'. cin reads one whitespace-delimited word; use cin.getline() to read a full line including spaces.

I/O for C-style Strings

Always pass the buffer size to cin.getline() to prevent buffer overflow, cin >> has no bounds checking for char arrays.

  • cout << charArray; prints until \0
  • cin >> charArray; reads one word (no spaces), no size limit, risky
  • cin.getline(arr, size); reads up to size-1 chars including spaces, safer
  • For safe string handling, std::string with std::getline is always preferred

Reading a C-style String

C++

cin.getline reads the whole line including spaces into the char array.

String Functions: strlen, strcpy, strcat, strcmp

The <cstring> header provides classic C functions for measuring, copying, concatenating, and comparing C-style strings.

<cstring> Functions

These functions all rely on the null terminator, passing a non-terminated char array to any of them is undefined behavior.

  • strlen(s): number of characters before \0 (not including \0)
  • strcpy(dst, src): copies src into dst, dst must be large enough
  • strcat(dst, src): appends src to the end of dst
  • strcmp(s1, s2): 0 if equal, negative if s1 < s2, positive if s1 > s2

strlen, strcat, strcpy, strcmp

C++

Four essential C string functions in one example.

C-style String vs std::string

Featurechar array (C-style)std::string
SizeFixed at declarationDynamic, grows automatically
Null terminatorRequired manuallyManaged internally
Assignmentstrcpy(dst, src)s1 = s2
Concatenationstrcat(dst, src)s1 + s2 or s1 += s2
Comparisonstrcmp(s1, s2)s1 == s2
Lengthstrlen(s)s.size() or s.length()
SafetyProne to buffer overflowBounds-safe

Knowledge Check

1. What is the index of the first element in a C++ array?

2. How do you find the number of elements in an array using sizeof?

3. How is a 2D array element arr[2][3] accessed?

4. What does passing an array to a function actually pass?

5. Which function returns the length of a C-style string?

6. What character marks the end of a C-style string?

7. What does strcmp(s1, s2) return when the two strings are equal?