How to use arrays in C++?

Introduction

C++ inherited arrays from C where they are used virtually everywhere. C++ provides abstractions that are easier to use and less error-prone (std::vector since C++98 and std::array since C++11), so the need for arrays does not arise quite as often as it does in C. However, when you read legacy code or interact with a library written in C, you should have a firm grasp on how arrays work.

Arrays on the Type Level and Accessing Elements

In C++, an array is a collection of elements of the same type stored in a contiguous block of memory. Each element in the array is accessed using an index. The index starts at 0 for the first element and goes up to the size of the array minus one.

Here's an example of declaring and accessing elements of an array in C++:

            
                int arr[5]; // Declaring an array with 5 elements of type int

                // Accessing elements of the array
                arr[0] = 1; // Assigning a value to the first element
                arr[1] = 2; // Assigning a value to the second element
                arr[2] = 3; // Assigning a value to the third element

                // Accessing elements for reading
                int x = arr[0]; // Assigning the value of the first element to variable x
                int y = arr[1]; // Assigning the value of the second element to variable y
                int z = arr[2]; // Assigning the value of the third element to variable z
            
        

Array Creation and Initialization

In C++, arrays can be created and initialized in multiple ways. The most common way is to declare the array and initialize it with a list of values enclosed in curly braces, known as initializer list.

Here's an example of creating and initializing an array in C++:

            
                int arr[] = {1, 2, 3}; // Creating and initializing an array with 3 elements

                // Accessing elements of the array
                int x = arr[0]; // Assigning the value of the first element to variable x
                int y = arr[1]; // Assigning the value of the second element to variable y
                int z = arr[2]; // Assigning the value of the third element to variable z
            
        

Assignment and Parameter Passing

In C++, arrays can be assigned to each other, and they can be passed as parameters to functions. However, when an array is passed as a parameter, it decays into a pointer to its first element. This means that the function receiving the array cannot determine its size.

Here's an example of assigning an array and passing it as a parameter:

            
                int arr1[] = {1, 2, 3}; // Creating and initializing array 1
                int arr2[3]; // Declaring array 2

                // Assigning array 1 to array 2
                for (int i = 0; i < 3; i++) {
                    arr2[i] = arr1[i];
                }

                // Passing an array as a parameter to a function
                void printArray(int arr[], int size) {
                    for (int i = 0; i < size; i++) {
                        std::cout << arr[i] << " ";
                    }
                    std::cout << std::endl;
                }

                // Calling the function with array 1
                printArray(arr1, 3);
            
        

Multidimensional Arrays and Arrays of Pointers

C++ supports multidimensional arrays, which are essentially arrays of arrays. Each element of a multidimensional array can be accessed using the indices of its dimensions.

Here's an example of declaring and accessing elements of a multidimensional array in C++:

            
                int arr[2][3]; // Declaring a multidimensional array with 2 rows and 3 columns

                // Accessing elements of the multidimensional array
                arr[0][0] = 1; // Assigning a value to the first element
                arr[0][1] = 2; // Assigning a value to the second element
                arr[0][2] = 3; // Assigning a value to the third element

                // Accessing elements for reading
                int x = arr[0][0]; // Assigning the value of the first element to variable x
                int y = arr[0][1]; // Assigning the value of the second element to variable y
                int z = arr[0][2]; // Assigning the value of the third element to variable z
            
        

C++ also allows arrays of pointers, where each element of the array is a pointer to another array. This can be useful in scenarios where the size of the array is not known at compile time.

Here's an example of declaring and accessing elements of an array of pointers in C++:

            
                int* arr[2]; // Declaring an array of pointers to int

                // Creating arrays and assigning them to the elements of the array of pointers
                int subArr1[] = {1, 2, 3};
                int subArr2[] = {4, 5, 6};
                arr[0] = subArr1; // Assigning subArr1 to the first element of the array
                arr[1] = subArr2; // Assigning subArr2 to the second element of the array

                // Accessing elements of the array of pointers
                int x = arr[0][0]; // Accessing the first element of the first sub-array
                int y = arr[1][1]; // Accessing the second element of the second sub-array
            
        

Common Pitfalls when Using Arrays

When using arrays in C++, there are some common pitfalls to avoid. One of them is accessing elements outside the bounds of the array, which can lead to undefined behavior. It's important to ensure that the index used to access elements is within the valid range of the array.

Another pitfall is confusing arrays with pointers. Although arrays decay into pointers when passed as parameters to functions, they are not the same. Arrays have a fixed size and cannot be resized, while pointers can be reassigned and can point to different memory locations.

Conclusion

Arrays are an important part of C++ programming, especially when dealing with legacy code or libraries written in C. It's crucial to understand how arrays work and how to use them correctly. By following the guidelines and examples provided in this article, you should now have a solid understanding of how to use arrays in C++.