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

2019-01-01 11:15发布

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

int boardAux[length][length] = {{0}};

8条回答
余生请多指教
2楼-- · 2019-01-01 11:26

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;
}
查看更多
若你有天会懂
3楼-- · 2019-01-01 11:28

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

查看更多
倾城一夜雪
4楼-- · 2019-01-01 11:29

This gives error:

int len;
scanf("%d",&len);
char str[len]="";

This also gives error:

int len=5;
char str[len]="";

But this works fine:

int len=5;
char str[len]; //so the problem lies with assignment not declaration

You need to put value in the following way:

str[0]='a';
str[1]='b'; //like that; and not like str="ab";
查看更多
旧人旧事旧时光
5楼-- · 2019-01-01 11:38

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

int a[n][m] ;
a[n][m]= {0};
查看更多
几人难应
6楼-- · 2019-01-01 11:40

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.

查看更多
闭嘴吧你
7楼-- · 2019-01-01 11:43

I am assuming that you are using a C99 compiler (with support for dynamically sized arrays). The problem in your code is that at the time when the compilers sees your variable declaration it cannot know how many elements there are in the array (I am also assuming here, from the compiler error that length is not a compile time constant).

You must manually initialize that array:

int boardAux[length][length];
memset( boardAux, 0, length*length*sizeof(int) );
查看更多
登录 后发表回答