Articles

Complete Guide to C++ Arrays

Learn how to use C++ arrays to store multiple values of the same type efficiently and master essential array operations in your C++ programs.

What are C++ arrays?

In C++, an array is a variable that can store multiple values of the same type. C++ arrays are fundamental data structures that allow you to organize related information in contiguous memory locations.

For example, suppose you need to store test scores for 30 students. Instead of creating 30 separate variables, you can create a single array :

int testScores[30];

Here, testScores is an array that can hold 30 integer values representing student scores.

Key characteristics

C++ arrays have several important features:

  • Fixed size: The size cannot be changed after declaration

  • Same data type: All elements must be of the same type

  • Zero-based indexing: First element is at index 0

  • Contiguous memory: Elements are stored next to each other in memory

  • No bounds checking: You must manually ensure valid array access

Related Course

Learn C: Arrays and Strings

Sharpen your programming skills by learning how to create, assess, and modify arrays and strings in C.Try it for free

Arrays vs vectors

If you’ve used C++ vectors before, you might wonder when to use arrays in C++ versus vectors.

Feature Arrays Vectors
Size Fixed at compile time Can grow/shrink dynamically
Performance Faster (no overhead) Slightly slower
Safety No bounds checking Built-in bounds checking
Memory Stack allocation Heap allocation

Use arrays when:

  • You know the exact size needed

  • Maximum performance is critical

  • Working with embedded systems

Use vectors when:

  • Size may change during runtime

  • You need safety features

  • Rapid development is a priority

Array declaration

The syntax for declaring arrays is:

dataType arrayName[arraySize];

Example:

int numbers[5]; // Array of 5 integers
double prices[10]; // Array of 10 doubles
char letters[26]; // Array of 26 characters

Important: Array size must be a compile-time constant and cannot use variables.

Array initialization

You can initialize arrays in several ways:

// Method 1: Specify all values
int numbers[5] = {10, 20, 30, 40, 50};
// Method 2: Let compiler determine size
int autoSize[] = {1, 2, 3, 4, 5}; // Size automatically becomes 5
// Method 3: Partial initialization (rest become 0)
int partial[5] = {1, 2}; // First two are 1,2; rest are 0
// Method 4: Initialize all to zero
int zeros[5] = {}; // All elements become 0
// Character arrays
char vowels[5] = {'a', 'e', 'i', 'o', 'u'};
char word[] = "Hello"; // Automatically sized for string

Accessing array elements

Use square brackets with the index to access elements. Arrays use zero-based indexing.

int scores[5] = {85, 90, 78, 92, 88};
// Access elements
int first = scores[0]; // 85 (first element)
int third = scores[2]; // 78 (third element)
int last = scores[4]; // 88 (last element)

Elements are stored consecutively in memory with addresses increasing by the size of the data type.

Modifying array elements

You can change array elements after creation:

int grades[5] = {75, 80, 85, 90, 95};
// Update individual elements
grades[0] = 80; // Change first element
grades[2] = grades[2] + 5; // Add 5 to third element
// Result: {80, 80, 90, 90, 95}

Array traversal

Example 1: Display array elements using a for loop

#include <iostream>
using namespace std;
int main() {
int numbers[5] = {10, 20, 30, 40, 50};
cout << "Array elements: ";
for (int i = 0; i < 5; i++) {
cout << numbers[i] << " ";
}
cout << endl;
return 0;
}

Output:

Array elements: 10 20 30 40 50

In this program, we have declared an array numbers with 5 elements. We use a for loop to iterate through the array from index 0 to 4. In each iteration, we print the element at the current index using numbers[i]. The loop variable i serves as the array index, allowing us to access each element sequentially.

Example 2: Take input and store in an array

#include <iostream>
using namespace std;
int main() {
int numbers[5];
cout << "Enter 5 numbers: " << endl;
// Store input from user to array
for (int i = 0; i < 5; i++) {
cin >> numbers[i];
}
cout << "You entered: ";
// Print array elements
for (int i = 0; i < 5; i++) {
cout << numbers[i] << " ";
}
cout << endl;
return 0;
}

Output:

Enter 5 numbers:
11
23
44
56
78
You entered: 11 23 44 56 78

Explanation:

Here, we first declare an array numbers without initializing it. We then use a for loop to take input from the user and store it in the array using cin >> numbers[i]. After storing all inputs, we use another for loop to display the array elements. This demonstrates how arrays can store user input dynamically during program execution.

Finding array size

Arrays don’t have a built-in size method. Use the sizeof operator:

int arr[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int size = sizeof(arr) / sizeof(arr[0]);
cout << "Array size: " << size << endl; // Output: 10

Important: This only works in the same scope where the array is declared. When passing arrays to functions, you must pass the size as a separate parameter.

Passing arrays to functions

Arrays are always passed as pointers to functions. You must pass the size separately since arrays lose size information when passed.

void printArray(int arr[], int size) {
for (int i = 0; i < size; i++) {
cout << arr[i] << " ";
}
cout << endl;
}
int main() {
int numbers[5] = {1, 2, 3, 4, 5};
printArray(numbers, 5); // Pass array and size
return 0;
}

Use const for read-only arrays to prevent accidental modification:

void displayArray(const int arr[], int size) {
// Function cannot modify arr elements
for (int i = 0; i < size; i++) {
cout << arr[i] << " ";
}
}

Multidimensional arrays

Arrays can have multiple dimensions for matrices, tables, and grids.

Example 3: Working with two-dimensional arrays

#include <iostream>
using namespace std;
int main() {
// 3x4 matrix (3 rows, 4 columns)
int matrix[3][4] = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}
};
// Access specific element
cout << "Element at [1][2]: " << matrix[1][2] << endl;
// Print entire matrix
cout << "Complete matrix:" << endl;
for (int row = 0; row < 3; row++) {
for (int col = 0; col < 4; col++) {
cout << matrix[row][col] << "\t";
}
cout << endl;
}
return 0;
}

Output:

Element at [1][2]: 7
Complete matrix:
1 2 3 4
5 6 7 8
9 10 11 12

In this example, we create a 2D array matrix with 3 rows and 4 columns. The array is initialized with values arranged in a grid format. We first access and print a specific element at position [1][2], which gives us 7 (second row, third column). Then we use nested for loops to traverse and print the entire matrix. The outer loop iterates through rows, while the inner loop iterates through columns, printing each element followed by a tab space for proper formatting.

When passing 2D arrays to functions, you must specify all dimensions except the first:

void processMatrix(int matrix[][4], int rows) {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < 4; j++) {
matrix[i][j] *= 2;
}
}
}

Common array operations

Here are some essential operations you’ll frequently perform with arrays in your C++ programs.

Finding maximum and minimum

int findMax(const int arr[], int size) {
int max = arr[0];
for (int i = 1; i < size; i++) {
if (arr[i] > max) {
max = arr[i];
}
}
return max;
}
int findMin(const int arr[], int size) {
int min = arr[0];
for (int i = 1; i < size; i++) {
if (arr[i] < min) {
min = arr[i];
}
}
return min;
}

Output:

Array elements: 45 23 67 12 89 34
Maximum value: 89
Minimum value: 12

The findMax function iterates through the array, comparing each element with the current maximum value. Similarly, findMin finds the smallest value by comparing elements. Both functions start with the first element as the initial value and then compare with remaining elements.

Calculating sum and average

#include <iostream>
using namespace std;
int calculateSum(const int arr[], int size) {
int sum = 0;
for (int i = 0; i < size; i++) {
sum += arr[i];
}
return sum;
}
double calculateAverage(const int arr[], int size) {
return static_cast<double>(calculateSum(arr, size)) / size;
}
int main() {
int scores[5] = {85, 92, 78, 96, 88};
cout << "Test scores: ";
for (int i = 0; i < 5; i++) {
cout << scores[i] << " ";
}
cout << endl;
int total = calculateSum(scores, 5);
double avg = calculateAverage(scores, 5);
cout << "Total sum: " << total << endl;
cout << "Average score: " << avg << endl;
return 0;
}

Output:

Test scores: 85 92 78 96 88
Total sum: 439
Average score: 87.8

The calculateSum function adds all array elements together using a loop. The calculateAverage function uses the sum and divides it by the array size. We use static_cast<double> to ensure floating-point division for accurate average calculation.

Searching for elements

int linearSearch(const int arr[], int size, int target) {
for (int i = 0; i < size; i++) {
if (arr[i] == target) {
return i; // Return index if found
}
}
return -1; // Return -1 if not found
}

Output:

Array elements: 10 25 30 45 60 75 80
Element 45 found at index 3

The linearSearch function examines each array element sequentially until it finds the target value or reaches the end. It returns the index position if the element is found, or -1 if not found. This is useful for locating specific values in unsorted arrays.

Array limitations and safety

Arrays have several limitations that require careful programming:

  1. No bounds checking: Accessing invalid indices causes undefined behavior

  2. Fixed size: Cannot resize after declaration

  3. Size information lost: Arrays decay to pointers in functions

  4. Buffer overflow risk: Writing beyond bounds can corrupt memory

Best practices for using C++ arrays

Following these guidelines will help you write safer and more efficient code when working with arrays.

  1. Always initialize arrays to avoid undefined behavior

  2. Validate array bounds before accessing elements

  3. Pass array size as a separate parameter to functions

  4. Use const for read-only array parameters

  5. Consider std::array or std::vector for additional safety features

Conclusion

C++ arrays are fundamental data structures that provide efficient storage for multiple values of the same type. Understanding arrays is essential for system-level programming, performance-critical applications, and working with legacy C code.

Frequently asked questions

1. What is the difference between arrays and vectors in C++?

Arrays have a fixed size determined at compile time and offer maximum performance with minimal overhead. Vectors are dynamic, can grow or shrink during runtime, and provide built-in safety features like bounds checking. Use arrays when size is known and performance is critical; use vectors when you need flexibility and safety.

2. How do you find the size of an array in C++?

Use the sizeof operator: int size = sizeof(array) / sizeof(array[0]);. This only works in the same scope where the array is declared. When arrays are passed to functions, you must pass the size as a separate parameter since arrays decay to pointers.

3. Can you change the size of an array after declaration?

No, C++ arrays have a fixed size that cannot be changed after declaration. If you need dynamic sizing, use std::vector or dynamically allocate memory using new and delete.

4. What happens if you access an array element outside its bounds?

Accessing an array element outside its bounds results in undefined behavior. This can lead to program crashes, data corruption, or security vulnerabilities. Always validate array indices before accessing elements.

5. How are multidimensional arrays stored in memory?

Multidimensional arrays are stored in row-major order in contiguous memory locations. For a 2D array arr[3][4], elements are stored as: arr[0][0], arr[0][1], arr[0][2], arr[0][3], arr[1][0], and so on.

6. Why do arrays decay to pointers when passed to functions?

This behavior is inherited from C for efficiency. Instead of copying the entire array, only the address of the first element is passed. This saves memory and time but loses size information, which is why you need to pass the size separately.

Codecademy Team

'The Codecademy Team, composed of experienced educators and tech experts, is dedicated to making tech skills accessible to all. We empower learners worldwide with expert-reviewed content that develops and enhances the technical skills needed to advance and succeed in their careers.'

Meet the full team