Arrays in C++
Arrays in C++ are a type of structured data that stores multiple elements of the same data type in consecutive memory locations. Arrays can be treated as a single entity or accessed individually via an integer index. They provide a way to store multiple values of the same type without declaring separate variables for each.
Purpose of Arrays
Arrays are useful for storing a fixed number of elements and performing operations on them efficiently, such as iterating over elements with loops. Contiguous memory storage allows for fast access to individual elements and can improve cache performance.
Limitations and Alternatives
Arrays have a fixed size defined at compile time. For collections that require dynamic resizing, or for frequent insertions and deletions, alternative containers may be more suitable:
- std::vector – a dynamic array that can grow or shrink during program execution.
- std::list – a linked list allowing efficient insertion and deletion at any position.
- std::deque – a double-ended queue supporting element addition or removal from both ends.
Declaring Arrays
Declaration requires the element type, an array name, and the number of elements in square brackets. Array indices begin at 0 and continue up to n-1.
Example of a one-dimensional integer array with five elements:
int array[5] = {0, 1, 2, 3, 4};
Example of a character array (string):
char someword[] = {'w', 'o', 'r', 'd', '\0'};
or:
char someword[] = "word";
The null character \0 marks the end of the string and is appended automatically in the second declaration.
Multidimensional Arrays
Arrays can also be multidimensional, such as two-dimensional arrays representing tables or matrices.
Example of a 3x4 integer matrix:
int array2D[3][4] = { {0, 2, 4, 6}, {1, 3, 5, 7}, {8, 9, 10, 11} };
The first index represents rows and the second index represents columns. Memory usage increases with additional dimensions.
Accessing Array Elements
Elements are accessed using indices. Example:
int x = array[2]; // retrieves the third element of the array
array2D[1][3] = 20; // sets the value of row 2, column 4 to 20
Summary
Arrays provide a simple and efficient method to store and manipulate multiple values of the same type. They are fixed in size, and for flexible or dynamically sized collections, standard library containers such as vector or list are recommended.