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

后端 未结 6 1683
独厮守ぢ
独厮守ぢ 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:18

    It seems like you are looking for a way to init a global array before main like described in Call a function before main? Usually I would recommend to avoid compiler specific extension but your code already is compiler specific and it seems ok for you. This is a gcc extension. It can cause strange errors. Other global objects could be uninitialized. Parts of this code probably causes undefined behavior. Just do it if you want to shoot you in your foot.

    #include 
    using namespace std;
    
    void beforeMain (void) __attribute__((constructor));
    
    int dp[100][100];
    void beforeMain (void) {
        memset(dp, -1, sizeof(dp));
    }
    
    int main() {
        std::cout << dp[0][0] << std::endl;
    }
    

提交回复
热议问题