Array Basics
An array is a fundamental data structure in C++ that provides a contiguous block of memory for storing multiple values of the same type. Because arrays can hold elements of any data type—integers, floating-point numbers, characters, or even complex objects—they are a versatile way to manage collections of data.
Declaring Arrays
Section titled “Declaring Arrays”To declare an array use the following structure:
type variable_name [kSizeConstant];The following is an integer array that can hold up to 5 values:
const int kSize = 4;int array [kSize];Declaring an array does not automatically initialize its values. If no initial values are provided, the contents of the array elements are indeterminate.
You can initialize an array at the time of declaration by assigning
it a list of values enclosed in braces {}. These values must be
separated by commas, and the compiler will determine the size of
the array based on the number of values provided.
int array[] = {1, 2, 3, 4, 5};When creating an array of numeric values, if you include the size of the array and use an initialization list, any values left out of the list will be set to 0. For example,
int my_array[5] = { 14 }; // 14, 0, 0, 0, 0Using Arrays
Section titled “Using Arrays”In C++, the name of an array refers to the memory address of its first element. This means that when you write the array’s name by itself, you’re essentially 🫵 pointing to the starting position of the array in memory.
// A location in your computer like: 0x7ffc6b2fc1d0cout << array_name << endl;To access individual elements, you use the array’s name followed by
square brackets containing the element’s index [integer]. The following
is an example of how to access elements in an array called my_array:
my_array[0]my_array[1]my_array[2]Filling Numeric Arrays
Section titled “Filling Numeric Arrays”You can use a for loop to fill a non-character array with values:
const int kSize = 4;int array[kSize];
for (int i = 0; i < kSize; ++i) { cout << "Enter the number for index " << i << endl; cin >> array[i];}Printing Numeric Arrays
Section titled “Printing Numeric Arrays”You can also use a for loop to print a non-character array with values:
for (int i = 0; i < kSize; ++i) { cout << array[i] << endl;}Overstepping Array Bounds
Section titled “Overstepping Array Bounds”One of the most common and dangerous errors when working with arrays is accessing elements outside their valid range.
In C++, your compiler will not produce an error if you use an index
outside of 0 to size - 1. Instead, it will treat the invalid
index as a memory offset from the first element, potentially overwriting
data that belongs to other variables or even other running programs.
This can lead to unpredictable behavior, crashes, or corrupted data.