How to initialize a 2D array with all values same?

后端 未结 6 1629
独厮守ぢ
独厮守ぢ 2021-01-29 10:49

I want to initialize a 2D array with -1 as all the value. I used memset() for this.

#include 
using namespace std;

int dp[100]         


        
6条回答
  •  不思量自难忘°
    2021-01-29 11:32

    As others have said, you can't call memset in the global scope. The most correct and clear vay is probably going to be something like

    #include 
    using namespace std;
    
    const int D1 = 100;
    const int D2 = 100;
    int dp[D1][D2];
    
    void initializeDp()
    {
        for (int i = 0; i < D1; i++) {
            for (int j = 0; j < D2; j++) {
                dp[i][j] = -1;
            }
        }
    }
    
    int main() {
        initializeDp();
        cout << dp[D1-1][D2-1];
        return 0;
    }
    

    If you count global variables as a good practice, obviously. I personally would use a 2d std::array, so it would contain its size itself

提交回复
热议问题