size of 2d array in c++
To determine the size of a 2D array in C++, you need to consider the number of rows and columns in the array. The size of a 2D array is calculated by multiplying the number of rows by the number of columns.
Here's an example code snippet that demonstrates how to find the size of a 2D array in C++:
#include <iostream>
int main() {
int arr[3][4]; // 2D array with 3 rows and 4 columns
int rows = sizeof(arr) / sizeof(arr[0]); // calculate the number of rows
int cols = sizeof(arr[0]) / sizeof(arr[0][0]); // calculate the number of columns
std::cout << "Number of rows: " << rows << std::endl;
std::cout << "Number of columns: " << cols << std::endl;
return 0;
}
In this example, we have declared a 2D array arr
with 3 rows and 4 columns.
To calculate the number of rows, we divide the total size of the array (sizeof(arr)
) by the size of the first row (sizeof(arr[0])
). This gives us the number of elements in a row.
Similarly, to calculate the number of columns, we divide the size of the first row (sizeof(arr[0])
) by the size of an individual element (sizeof(arr[0][0])
). This gives us the number of elements in a column.
The output of this code will be:
Number of rows: 3
Number of columns: 4
This tells us that the 2D array has 3 rows and 4 columns.