how to find 2d array size in c++

后端 未结 9 770
余生分开走
余生分开走 2020-12-23 12:14

How do I find the size of a 2D array in C++? Is there any predefined function like sizeof to determine the size of the array?

Also, can anyone tell me h

相关标签:
9条回答
  • 2020-12-23 12:55

    Along with the _countof() macro you can refer to the array size using pointer notation, where the array name by itself refers to the row, the indirection operator appended by the array name refers to the column.

    #include <iostream>
    #include <iomanip>
    
    using namespace std;
    
    int main()
    {
        int beans[3][4]{
            { 1, 2, 3, 4 }, 
            { 5, 6, 7, 8 }, 
            { 9, 10, 11, 12 }
        };
    
        cout << "Row size = " << _countof(beans)  // Output row size
            << "\nColumn size = " << _countof(*beans);  // Output column size
        cout << endl;
    
        // Used in a for loop with a pointer.
    
        int(*pbeans)[4]{ beans };
    
        for (int i{}; i < _countof(beans); ++i) {
    
            cout << endl;
    
            for (int j{}; j < _countof(*beans); ++j) {
    
                cout << setw(4) << pbeans[i][j];
            }
        };
    
        cout << endl;
    }
    
    0 讨论(0)
  • 2020-12-23 12:57

    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
    
    0 讨论(0)
  • 2020-12-23 13:06

    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 */
    
    0 讨论(0)
提交回复
热议问题