25% complete
Arrays in C++
Arrays are fundamental data structures in C++ that allow you to store multiple values of the same type in contiguous memory locations. They provide an efficient way to manage collections of data under a single variable name with indexed access.
What You'll Learn
- How to declare and initialize arrays
- Accessing and modifying array elements
- Common array operations and techniques
- Working with multi-dimensional arrays
- The relationship between arrays and pointers
- Passing arrays to functions
- Array limitations and alternatives in C++
Array Basics in C++
An array in C++ is a collection of elements of the same data type, stored in adjacent memory locations. Each element can be accessed using an index, which starts from 0 for the first element.
Declaring Arrays
The basic syntax for declaring an array in C++ is:
1dataType arrayName[arraySize];
Here are some examples of array declarations:
1// Array of 5 integers2int numbers[5];34// Array of 10 characters5char letters[10];67// Array of 3 doubles8double prices[3];910// Array of 4 booleans11bool flags[4];
Important Note
In C++, array size must be a constant expression known at compile time when declaring a fixed-size array. The array size cannot be a variable whose value is determined at runtime (unless you use dynamic memory allocation).
Initializing Arrays
There are several ways to initialize arrays in C++:
1// Method 1: Initialize at declaration with values2int scores[5] = {90, 85, 78, 92, 88};34// Method 2: Initialize with fewer values than the size5// Remaining elements are initialized to 06int partialScores[5] = {90, 85, 78}; // Elements at index 3 and 4 will be 078// Method 3: Let the compiler determine the size based on elements9int autoSized[] = {10, 20, 30, 40, 50}; // Size is 51011// Method 4: Initialize all elements to the same value12int allZeros[5] = {}; // All elements initialized to 013int allOnes[5] = {1, 1, 1, 1, 1};1415// Method 5: Initialize specific elements16int sparse[10] = {0}; // First element is 0, rest are also 017sparse[5] = 50; // Only set the 6th element1819// C++11 and later: Uniform initialization syntax20int modern[5]{10, 20, 30, 40, 50};
Accessing Array Elements
Array elements are accessed using their index in square brackets. Remember that array indices start at 0 in C++.
1#include <iostream>2using namespace std;34int main() {5 int scores[5] = {90, 85, 78, 92, 88};67 // Accessing individual elements8 cout << "First element: " << scores[0] << endl; // 909 cout << "Third element: " << scores[2] << endl; // 7810 cout << "Last element: " << scores[4] << endl; // 881112 // Modifying elements13 scores[1] = 95; // Change the second element14 cout << "Updated second element: " << scores[1] << endl; // 951516 // Iterating through all elements17 cout << "All scores: ";18 for (int i = 0; i < 5; i++) {19 cout << scores[i] << " ";20 }21 cout << endl;2223 return 0;24}
Warning: Array Bounds
C++ does not perform automatic boundary checking on arrays. Accessing elements outside the array bounds (like scores[10]
for an array of size 5) leads to undefined behavior, which might cause crashes or subtle bugs that are hard to detect.
Common Array Operations
Finding Array Size
Unlike some programming languages, C++ does not store the size of an array as part of the array itself. There are several ways to determine the size:
1#include <iostream>2using namespace std;34int main() {5 int numbers[] = {10, 20, 30, 40, 50};67 // Method 1: sizeof operator (works for fixed-size arrays)8 int size = sizeof(numbers) / sizeof(numbers[0]);9 cout << "Array size: " << size << endl; // 51011 // Method 2: C++11 and later - std::size (since C++17)12 // #include <iterator>13 // cout << "Array size: " << std::size(numbers) << endl;1415 // Method 3: C++11 and later - range-based for loop doesn't need size16 cout << "Array elements: ";17 for (int num : numbers) {18 cout << num << " ";19 }20 cout << endl;2122 return 0;23}
Searching an Array
Here's how to search for an element in an array:
1#include <iostream>2using namespace std;34int main() {5 int numbers[] = {10, 20, 30, 40, 50};6 int size = sizeof(numbers) / sizeof(numbers[0]);7 int searchValue = 30;8 bool found = false;9 int position = -1;1011 // Linear search12 for (int i = 0; i < size; i++) {13 if (numbers[i] == searchValue) {14 found = true;15 position = i;16 break; // Exit the loop once found17 }18 }1920 if (found) {21 cout << searchValue << " found at position " << position << endl;22 } else {23 cout << searchValue << " not found in the array" << endl;24 }2526 return 0;27}
Sorting an Array
You can sort arrays either by implementing sorting algorithms yourself or using the standard library:
1#include <iostream>2#include <algorithm> // For std::sort3using namespace std;45int main() {6 int numbers[] = {45, 12, 85, 32, 89, 39, 69, 44, 42, 1, 6, 8};7 int size = sizeof(numbers) / sizeof(numbers[0]);89 // Before sorting10 cout << "Before sorting: ";11 for (int i = 0; i < size; i++) {12 cout << numbers[i] << " ";13 }14 cout << endl;1516 // Sort the array using std::sort17 sort(numbers, numbers + size);1819 // After sorting20 cout << "After sorting: ";21 for (int i = 0; i < size; i++) {22 cout << numbers[i] << " ";23 }24 cout << endl;2526 return 0;27}
Multi-dimensional Arrays
C++ supports multi-dimensional arrays, which are essentially arrays of arrays. The most common type is the two-dimensional array, often used to represent matrices or grids.
Declaring and Initializing 2D Arrays
1#include <iostream>2using namespace std;34int main() {5 // Declaration of a 3x4 2D array (3 rows, 4 columns)6 int matrix[3][4];78 // Initialization with values9 int grid[3][3] = {10 {1, 2, 3}, // Row 011 {4, 5, 6}, // Row 112 {7, 8, 9} // Row 213 };1415 // Partial initialization (remaining elements set to 0)16 int partialGrid[3][3] = {17 {1, 2},18 {4}19 };2021 // Accessing elements22 cout << "Element at grid[1][2]: " << grid[1][2] << endl; // 62324 // Modifying elements25 grid[0][0] = 10;26 cout << "Modified element at grid[0][0]: " << grid[0][0] << endl; // 102728 return 0;29}
Iterating Through 2D Arrays
1#include <iostream>2using namespace std;34int main() {5 int grid[3][3] = {6 {1, 2, 3},7 {4, 5, 6},8 {7, 8, 9}9 };1011 // Print the grid12 cout << "Grid contents:" << endl;13 for (int row = 0; row < 3; row++) {14 for (int col = 0; col < 3; col++) {15 cout << grid[row][col] << " ";16 }17 cout << endl; // New line after each row18 }1920 // Sum of all elements21 int sum = 0;22 for (int row = 0; row < 3; row++) {23 for (int col = 0; col < 3; col++) {24 sum += grid[row][col];25 }26 }27 cout << "Sum of all elements: " << sum << endl;2829 // Using C++11 range-based for loop (not as common for 2D arrays)30 sum = 0;31 for (auto &row : grid) {32 for (int value : row) {33 sum += value;34 }35 }3637 return 0;38}
Common 2D Array Applications
- Game boards (chess, tic-tac-toe)
- Pixel-based graphics (image processing)
- Mathematical matrices
- Spreadsheet-like data
- Maze or map representations
Higher-Dimensional Arrays
C++ supports arrays with 3 or more dimensions:
// 3D array (2x3x4)int cube[2][3][4];// 4D arrayint hyperCube[2][3][4][5];// Initialization exampleint threeDArray[2][2][2] = {{{1, 2}, {3, 4}},{{5, 6}, {7, 8}}};
Arrays and Pointers
In C++, arrays and pointers are closely related. The name of an array can be thought of as a pointer to its first element.
1#include <iostream>2using namespace std;34int main() {5 int numbers[5] = {10, 20, 30, 40, 50};67 // Array name is a pointer to the first element8 int *ptr = numbers; // Same as &numbers[0]910 // Accessing elements using pointer arithmetic11 cout << "First element: " << *ptr << endl; // 1012 cout << "Second element: " << *(ptr + 1) << endl; // 2013 cout << "Third element: " << *(ptr + 2) << endl; // 301415 // Equivalent array notation16 cout << "First element: " << numbers[0] << endl; // 1017 cout << "Second element: " << numbers[1] << endl; // 2018 cout << "Third element: " << numbers[2] << endl; // 301920 // Pointer arithmetic21 ptr++; // ptr now points to the second element22 cout << "Element at ptr: " << *ptr << endl; // 202324 return 0;25}
Array Decay
When an array is passed to a function, it "decays" into a pointer to its first element. This means that information about the array's size is lost. This is why functions that take arrays as parameters often require the size to be passed as a separate argument.
Passing Arrays to Functions
There are several ways to pass arrays to functions in C++:
1#include <iostream>2using namespace std;34// Method 1: Using array notation (actually passes a pointer)5void displayArray(int arr[], int size) {6 for (int i = 0; i < size; i++) {7 cout << arr[i] << " ";8 }9 cout << endl;10}1112// Method 2: Using pointer notation (equivalent to Method 1)13void displayArrayWithPointer(int *arr, int size) {14 for (int i = 0; i < size; i++) {15 cout << arr[i] << " ";16 }17 cout << endl;18}1920// Method 3: Using fixed-size array notation (size is part of type)21void displayFixedArray(int arr[5]) {22 // Still doesn't know the true size; 5 is just part of the type23 for (int i = 0; i < 5; i++) {24 cout << arr[i] << " ";25 }26 cout << endl;27}2829// Method 4: Using a reference to an array (preserves size information)30template <size_t N>31void displayArrayWithSize(int (&arr)[N]) {32 for (int i = 0; i < N; i++) {33 cout << arr[i] << " ";34 }35 cout << endl;36}3738// Modifying an array in a function39void doubleValues(int arr[], int size) {40 for (int i = 0; i < size; i++) {41 arr[i] *= 2; // Modifies the original array42 }43}4445int main() {46 int numbers[5] = {10, 20, 30, 40, 50};47 int size = sizeof(numbers) / sizeof(numbers[0]);4849 cout << "Original array: ";50 displayArray(numbers, size);5152 displayArrayWithPointer(numbers, size);53 displayFixedArray(numbers);54 displayArrayWithSize(numbers);5556 doubleValues(numbers, size);5758 cout << "Array after doubling: ";59 displayArray(numbers, size);6061 return 0;62}
Array Limitations and Modern Alternatives
While arrays are fundamental in C++, they have several limitations:
- Fixed size that must be known at compile time (for stack-allocated arrays)
- No built-in bounds checking
- Cannot be easily resized
- No built-in methods for common operations
- Size information is lost when passed to functions
Modern C++ offers several alternatives to traditional arrays:
Alternative | Description | Advantages |
---|---|---|
std::vector | Dynamic array implementation |
|
std::array | Fixed-size array wrapper |
|
std::span | View of a contiguous sequence (C++20) |
|
1#include <iostream>2#include <vector> // For std::vector3#include <array> // For std::array4using namespace std;56int main() {7 // std::vector example8 vector<int> vec = {10, 20, 30, 40, 50};9 vec.push_back(60); // Add a new element1011 cout << "Vector contents: ";12 for (int num : vec) {13 cout << num << " ";14 }15 cout << endl;1617 // Using vector's methods18 cout << "Vector size: " << vec.size() << endl;19 cout << "Element at index 2: " << vec.at(2) << endl; // Bounds-checked access2021 // std::array example (fixed size, but with benefits over C-style arrays)22 array<int, 5> arr = {10, 20, 30, 40, 50};2324 cout << "Array contents: ";25 for (int num : arr) {26 cout << num << " ";27 }28 cout << endl;2930 // Using array's methods31 cout << "Array size: " << arr.size() << endl;32 cout << "Element at index 2: " << arr.at(2) << endl; // Bounds-checked access3334 return 0;35}
Common Array Algorithms and Techniques
Finding Maximum and Minimum
1int findMax(int arr[], int size) {2 int max = arr[0];3 for (int i = 1; i < size; i++) {4 if (arr[i] > max) {5 max = arr[i];6 }7 }8 return max;9}1011int findMin(int arr[], int size) {12 int min = arr[0];13 for (int i = 1; i < size; i++) {14 if (arr[i] < min) {15 min = arr[i];16 }17 }18 return min;19}
Reversing an Array
1void reverseArray(int arr[], int size) {2 int start = 0;3 int end = size - 1;45 while (start < end) {6 // Swap elements7 int temp = arr[start];8 arr[start] = arr[end];9 arr[end] = temp;1011 // Move pointers12 start++;13 end--;14 }15}
Calculating Average
1double calculateAverage(int arr[], int size) {2 if (size == 0) return 0;34 int sum = 0;5 for (int i = 0; i < size; i++) {6 sum += arr[i];7 }89 return static_cast<double>(sum) / size;10}
Array Rotation
1// Rotate array left by one position2void rotateLeft(int arr[], int size) {3 if (size <= 1) return;45 int temp = arr[0];6 for (int i = 0; i < size - 1; i++) {7 arr[i] = arr[i + 1];8 }9 arr[size - 1] = temp;10}1112// Rotate array right by one position13void rotateRight(int arr[], int size) {14 if (size <= 1) return;1516 int temp = arr[size - 1];17 for (int i = size - 1; i > 0; i--) {18 arr[i] = arr[i - 1];19 }20 arr[0] = temp;21}
Best Practices
- Use modern C++ containers like std::vector or std::array instead of raw arrays when possible
- Check array bounds before accessing elements to prevent buffer overflows
- Pass arrays with their size to functions to ensure proper handling
- Consider const correctness for arrays that shouldn't be modified
- Use range-based for loops for cleaner iteration (C++11 and later)
- Prefer std::algorithms for common operations (sorting, searching, etc.)
Summary
Arrays in C++ provide a fundamental way to store and manipulate collections of data. While they have some limitations compared to more modern container types, understanding arrays is essential for C++ programming and forms the basis for understanding more advanced data structures.
In this tutorial, we covered:
- Basic array declaration and initialization
- Accessing and modifying array elements
- Common array operations
- Multi-dimensional arrays
- The relationship between arrays and pointers
- Techniques for passing arrays to functions
- Modern alternatives to traditional arrays
As you continue your C++ journey, you'll find that the concepts learned here will apply to more sophisticated container types like vectors, which offer the benefits of arrays with additional features like dynamic resizing and bounds checking.
Related Tutorials
Learn about pointers and their relationship with arrays in C++.
Learn moreLearn about the Standard Template Library including vectors, a dynamic array alternative.
Learn moreUnderstand dynamic memory allocation and management in C++.
Learn more