how to find 2d array size in c++

后端 未结 9 831
余生分开走
余生分开走 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 
    #include 
    
    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;
    }
    

提交回复
热议问题