Arrays in C++

Arrays in C++

Arrays in C++ are fundamental concepts that provide you with an efficient way to store and manage multiple values of the same data type in memory. Whether you are using simple lists or complex data structures, arrays will help you to write efficient and scalable C++ code. In this article, we will discuss an array, how to create, initialize, update, access, traverse, and find the size of an array, with its characteristics, comparison, and best practices in C++.

Table of Contents:

What is an Array?

What is an Array

In C++, an array is a collection of elements of the same data type stored in a contiguous memory location. It stores multiple values with a single variable name, which makes it easier for the array to manage related data.

Example:

Cpp

Output:

Array

Explanation: The code shows how an integer array numbers is initialized with five elements, 10, 20, 30, 40, and 50 in a C++ program, and the first and third element is printed using their indices respectively.

Characteristics of Array in C++

  1. Pointer Compatible: The name of an array acts as a pointer to the first element.
  2. Fixed Size: The size cannot be changed after the declaration.
  3. Contiguous Memory: The elements are stored in adjacent memory locations.
  4. Zero-Based Indexing: The first element is at index 0.
  5. Fast Access: Direct indexing allows O(1) access time.
  6. Same Data Type: All elements must be of the same type.
  7. No Bounds Checking: Accessing out-of-range indices leads to undefined behavior.
  8. Static & Dynamic Allocation: This can be declared with a fixed size or allocated dynamically.
  9. Loop-Friendly: Arrays can be easily accessed and modified using loops.
  10. Multi-Dimensional Support: They support 2D and 3D arrays.

Declaring and Initializing Arrays in C++

a. Declaring an Array

Declaring an Array

You can declare an array in C++ by specifying the data type with the array name and size in the square brackets.

Syntax:

data_type array_name[size]; 

Example:

int numbers[5];  // Declares an integer array with 5 elements

Explanation: The above line of code shows that an integer array named numbers is declared with a size of 5.

b. Initializing an Array

Initializing an Array

You can initialize an array in different ways at the time of its declaration in C++.

1. Default Initialization

The default initialization of an array occurs when the array is declared but not initialized, and its elements are undefined or contain garbage values. Also, you must know that if an array is declared globally or as a static variable, then its elements are automatically initialized to zero, and if there is a local variable, then it contains garbage values.

Example:

int numbers[3]; // Uninitialized array

Explanation: The above line of code shows that an integer array named numbers is declared with the size of 3, but as it is initialized, its elements can contain undefined values.

2. Explicit Initialization

In explicit initialization, the values are assigned at the time of declaration in C++.

Example:

int numbers[5] = {10, 20, 30, 40, 50}; // Initializing all elements

Explanation: The above line of code shows that an integer array named numbers is declared with size 5 and initialized with five elements: 10, 20, 30, 40, and 50.

3. Partial Initialization

When an array is initialized with fewer values than its declaration size then the remaining elements are set to 0 automatically, thus it is known as partial initialization.

Note: It is only applied when the array is declared with explicit values.

Example:

int numbers[5] = {10, 20}; // Remaining elements will be set to 0

Explanation: The above line of code shows how an integer array named numbers with five elements shows only partial initialization with the first two elements 10 and 20, and the remaining elements are automatically set to 0.

4. Initializing Arrays with Loops

The for loop is used to initialize the arrays when working with large arrays, as it provides flexibility and sets values based on calculations, user input, and specific patterns.

Example:

Cpp

Output:

Initializing Arrays with Loops

Explanation: The code shows how an integer array of numbers with five elements is initialized using a loop with multiples of 10, and then it prints the values using another loop.

Accessing Array Elements in C++

Accessing Array Elements in C++

The elements of an array in C++ are accessed using their index, which starts from 0. The syntax of an array is array_name[index], where the index represents the position of the element. And, for accessing the multi-dimensional arrays, multiple indices are used, such as array[row][column] for 2D arrays. Also, accessing the elements beyond the array size will lead to undefined behavior.

1. Accessing Elements Using Indexing

Elements of a one-dimensional array are accessed by using their index, which starts from 0.

Example:

Cpp

Output:

Accessing Elements Using Indexing

Explanation: The code shows how the first and third elements of an integer array of numbers are accessed using their respective indices. Then the second element is modified, and then the updated value is printed to the console.

2. Accessing Elements Using Loops

Multi-dimensional arrays are accessed by using loops, as loops make it easy to traverse arrays without manually writing their indices.

Example:

Cpp

Output:

Accessing Elements Using Loops

Explanation: The code shows how an integer array number is initialized with five elements, and its elements are accessed using a loop and then printed to the console after each iteration with its index.

3. Accessing Array Elements Using Pointers

Arrays in C++ are closely related to pointers and can be used for accessing the arrays, and the name of an array acts as a pointer to the first element.

Example:

Cpp

Output:

Accessing Array Elements Using Pointers

Explanation: The code shows how an integer array of numbers is initialized with the three elements: 10, 20, and 30. Its first and second elements are accessed using a pointer and then printed to the console.

Get 100% Hike!

Master Most in Demand Skills Now!

Updating an Array in C++

The arrays in C++ can be updated by changing the values of their elements using their index. Also, the size of an array cannot be changed.

Example:

Cpp

Output:

Updating an Array

Explanation: The code shows how an initialized integer array numbers with five elements updates its second and fourth element with the values 25 and 45, and then the elements of the updated array are accessed and printed to the console by using the for loop.

Traversing an Array in C++

Traversing an Array in C++

The arrays in C++ can be traversed easily by using the for loop. Traversing means that each element of an array can be accessed. It is used for displaying, changing, and performing operations on the array elements.

Example:

Cpp

Output:

Traversing an Array in C++

Explanation: The code shows how an integer array of numbers initialized with five elements is traversed using the for loop, and its elements are printed after the iteration.

Types of Arrays in C++

There are two main types of Arrays that you can commonly use in C++ programming.

1. One-Dimensional Array 

One-Dimensional Array

In C++, a one-dimensional array is an array that forms a linear collection of elements that are stored in a contiguous memory location. You can access each element using the indices in this type of array. Also, it provides efficient storage and retrieval of multiple elements of the same data type in a C++ program. 

Example:

Cpp

Output:

One-Dimensional Array 

Explanation: The code shows how a one-dimensional integer array number is declared and initialized with the five elements, and then it uses a loop to iterate through the array and print the elements with their index.

2. Multi-Dimensional Array

Multi-Dimensional Array

A multi-dimensional array is an array in which each element of the array can store another array. It can also be called as an array of arrays. There are two types of multidimensional arrays: two-dimensional arrays and three-dimensional arrays. 

a. Two-Dimensional Array (2D Array)

A 2D array is a type of array with rows and columns. The row and column are its indices, which are used to declare it in a C++ program.

Example:

Cpp

Output:

Multi-Dimensional Array

Explanation: The code shows how a two-dimensional integer array matrix is declared and initialized with the elements, and then it uses nested loops to iterate through the array and prints the matrix elements in row-major order.

b. Three-Dimensional Array (3D Array)

A 3D array in C++ is an array of 2D arrays. It has three indices: depth, row, and column, which are used for representing 3D spaces such as a cube or any game environment.

Example:

Cpp

Output:

Three-Dimensional Array

Explanation: The code shows how a 3D array cube with dimensions 2*2*3 is initialized and iterated using the three nested loops, and then each layer of the cube is printed separately to the console.

Size of an Array in C++

The size of an array in C++ can be determined using the sizeof operator on the data types and the number of elements in the array.

Formula to Find Array Size:

size = sizeof(array) / sizeof(array[0]);

Here, the sizeof(array) is the total memory occupied by the array, and the sizeof(array[0]) is the memory occupied by one element of that array.

Example:

Cpp

Output:

Size of an Array

Explanation: The code shows how an integer array numbers is declared and its size is calculated by dividing the total memory occupied by the array (sizeof(numbers)) by the size of a single element (sizeof(numbers[0])), and then the size of the array is printed to the console.

Passing an Array to a Function in C++

Arrays in C++ are passed to the functions using pointers because arrays can be converted into pointers when they are passed as function arguments in the program.

There are three ways to pass an array to a function:

  1. By using a pointer 
  2. By using a sized array parameter
  3. By using the std::vector 

Example:

Cpp

Output:

Passing an Array to a Function

Explanation: The code shows how an array is passed to a function, printArray, to print the array elements, as it calculates the array size using the sizeof operator and then calls the function printArray to print the elements to the console.

Arrays in Expressions in C++

Arrays in C++ can be used in expressions where the individual elements or an entire array can interact with the operators.

Common Use Cases:

  1. The elements of the array can be used in mathematical expressions for arithmetic calculations.
  2. The values of the array elements can be assigned and changed based on expressions.
  3. The elements of the array can be compared individually.
  4. Arrays can be passed to functions and used in expressions as a function call.

Example:

Cpp

Output:

Arrays in Expressions

Explanation: The code shows how an array can be used in expressions in C++ to perform an arithmetic and comparison operation, as the sum of the first two elements is calculated, the third element is modified by multiplying with 2, and the fourth and second elements are compared using greater than, and then the results are printed to the console.

Arrays vs other Data Structures in C++

Feature Arrays Linked Lists Stacks & Queues Vectors (C++ STL)
Memory Allocation Contiguous (Fixed size) Dynamic (Node-based) Contiguous (Stack-like) Dynamic (Resizable)
Access Speed Fast (O(1)) via indexing Slower (O(n)) traversal O(1) (Top/Front access) Fast (O(1)) indexing
Insertion/Deletion Costly (O(n)) shifting Efficient (O(1) at head) O(1) (Push/Pop) Efficient
Flexibility Fixed-size Dynamic size Limited operations Dynamic size
Usage Simple storage, fast access Efficient insert/delete LIFO (Stack), FIFO (Queue) Hybrid of arrays/lists

Best Practices for Using Arrays in C++

  1. You should define the array size using const int SIZE = 10; instead of complex values to improve the maintainability.
  2. Always make sure that their index values are within the valid limits to avoid undefined behavior.
  3. Use the std::vector instead of raw arrays for safer memory management and dynamic resizing.
  4. You should always initialize the arrays during or after the declaration to avoid garbage values.
  5. You can use the for loops for efficient element processing.
  6. You must use pointers and references when passing the large arrays to the functions to avoid unnecessary memory copying in the program.
  7. Always prefer the row-major order traversal for better cache performance.
  8. You should always use the constants and the macros instead of complex indices and sizes.

Conclusion

From the above article, we can conclude that arrays in C++ play an important role by storing multiple values of the same type in contiguous memory, which allows fast accessing of the elements using the indexing. As we have discussed above, the fixed size and lack of boundary checks of the arrays can lead to undefined behavior if they are used in an incorrect manner. So, by understanding the array, its types, updating, and traversal, you can easily write a C++ program with an array.

FAQs on Arrays in C++

Q1. What is an array?

An array is a list of elements of the same data type stored in contiguous memory locations.

Q2. How can I declare an array in C++?

You can declare an array by using the declaration syntax data_type array_name[size];.

Q3. Can I change the size of an array after declaration?

No, you can not change the size of an array after declaring it, and if you want to change it, then use the std::vector for dynamic resizing.

Q4. How can I initialize an array in C++?

You can initialize an array in C++ by using the array initialization syntax.

Q5. What will happen if I access an out-of-bounds index?

If you access an out-of-bounds index, then an undefined behavior will occur, leading to crashes or unexpected values.

About the Author

Technical Research Analyst - Full Stack Development

Kislay is a Technical Research Analyst and Full Stack Developer with expertise in crafting Mobile applications from inception to deployment. Proficient in Android development, IOS development, HTML, CSS, JavaScript, React, Angular, MySQL, and MongoDB, he’s committed to enhancing user experiences through intuitive websites and advanced mobile applications.

Full Stack Developer Course Banner