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

前端 未结 10 1122
甜味超标
甜味超标 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:33

    The array is not initialized with the memory specified anf throws an error variable sized array may not be initialised I prefer usual way of initialization,

    for (i = 0; i <= bins; i++)
            arr[i] = 0;
    
    0 讨论(0)
  • 2020-11-22 07:35

    You receive this error because in C language you are not allowed to use initializers with variable length arrays. The error message you are getting basically says it all.

    6.7.8 Initialization

    ...

    3 The type of the entity to be initialized shall be an array of unknown size or an object type that is not a variable length array type.

    0 讨论(0)
  • 2020-11-22 07:38

    After declaring the array

    int boardAux[length][length];
    

    the simplest way to assign the initial values as zero is using for loop, even if it may be a bit lengthy

    int i, j;
    for (i = 0; i<length; i++)
    {
        for (j = 0; j<length; j++)
            boardAux[i][j] = 0;
    }
    
    0 讨论(0)
  • 2020-11-22 07:40

    For C++ separate declaration and initialization like this..

    int a[n][m] ;
    a[n][m]= {0};
    
    0 讨论(0)
  • 2020-11-22 07:41

    Simply declare length to be a cons, if it is not then you should be allocating memory dynamically

    0 讨论(0)
  • 2020-11-22 07:48

    You cannot do it. C compiler cannot do such a complex thing on stack.

    You have to use heap and dynamic allocation.

    What you really need to do:

    • compute size (nmsizeof(element)) of the memory you need
    • call malloc(size) to allocate the memory
    • create an accessor: int* access(ptr,x,y,rowSize) { return ptr + y*rowSize + x; }

    Use *access(boardAux, x, y, size) = 42 to interact with the matrix.

    0 讨论(0)
提交回复
热议问题