2D C-style arrays in C++ are essentially arrays of arrays. Each element in a 2D array is itself a 1DÂ array.
Here's how you can create and work with 2D C-style arrays:
The following example demonstrates how we can create a 2D C-style array, and optionally provide it with initial values:
// Declare a 3x3 int array
int arr[3][3];
// Initialize with values
int arr[3][3] = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
Here, we show how to access and modify elements in a 2D C-style array:
// Access individual elements
// Accessing row 1, column 2
int val = arr[1][2];
// Modify an element
// Modifying row 0, column 0
arr[0][0] = 10;
We can pass a 2D C-style array to a function in the usual way:
#include <iostream>
void print2DArray(int arr[][3], int rows) {
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < 3; ++j) {
std::cout << arr[i][j] << ' ';
}
std::cout << '\n';
}
}
int main() {
int arr[2][3] = {{1, 2, 3}, {4, 5, 6}};
print2DArray(arr, 2);
}
1 2 3
4 5 6
Note that when passing a 2D array to a function, you must specify all dimensions except the first one.
2D arrays are laid out contiguously in memory, so you can also treat them as a 1DÂ array:
int arr[2][3] = {{1, 2, 3}, {4, 5, 6}};
// Treat as 1D array
for (int i = 0; i < 6; ++i) {
std::cout << *(*arr + i) << ' ';
}
However, for more complex and dynamic 2D arrays, consider using a std::vector<std::vector<int>>
instead. It offers more flexibility and convenience at the cost of some performance overhead.
Understanding how to work with 2D C-style arrays is important for certain applications and for understanding how arrays are laid out in memory, but in modern C++, 2D std::vector
s or other library containers are often preferred for their safety and ease of use.
Answers to questions are automatically generated and may not have been reviewed.
A detailed guide to working with classic C-style arrays within C++, and why we should avoid them where possible