C compile error: “Variable-sized object may not be initialized”

前端 未结 10 1306
甜味超标
甜味超标 2020-11-22 07:22

Why do I receive the error \"Variable-sized object may not be initialized\" with the following code?

int boardAux[length][length] = {{0}};
10条回答
  •  暖寄归人
    2020-11-22 07:54

    The question is already answered but I wanted to point out another solution which is fast and works if length is not meant to be changed at run-time. Use macro #define before main() to define length and in main() your initialization will work:

    #define length 10
    
    int main()
    {
        int boardAux[length][length] = {{0}};
    }
    

    Macros are run before the actual compilation and length will be a compile-time constant (as referred by David Rodríguez in his answer). It will actually substitute length with 10 before compilation.

提交回复
热议问题