how to find 2d array size in c++ how to find 2d array size in c++ arrays arrays

how to find 2d array size in c++


Suppose you were only allowed to use array then you could find the size of 2-d array by the following way.

  int ary[][5] = { {1, 2, 3, 4, 5},                   {6, 7, 8, 9, 0}                 };  int rows =  sizeof ary / sizeof ary[0]; // 2 rows    int cols = sizeof ary[0] / sizeof(int); // 5 cols


Use an std::vector.

std::vector< std::vector<int> > my_array; /* 2D Array */my_array.size(); /* size of y */my_array[0].size(); /* size of x */

Or, if you can only use a good ol' array, you can use sizeof.

sizeof( my_array ); /* y size */sizeof( my_array[0] ); /* x size */


#include <bits/stdc++.h>using namespace std;int main(int argc, char const *argv[]){    int arr[6][5] = {        {1,2,3,4,5},        {1,2,3,4,5},        {1,2,3,4,5},        {1,2,3,4,5},        {1,2,3,4,5},        {1,2,3,4,5}    };    int rows = sizeof(arr)/sizeof(arr[0]);    int cols = sizeof(arr[0])/sizeof(arr[0][0]);    cout<<rows<<" "<<cols<<endl;    return 0;}

Output: 6 5