Why do I receive the error \"Variable-sized object may not be initialized\" with the following code?
int boardAux[length][length] = {{0}};
int size=5;
int ar[size ]={O};
/* This operation gives an error -
variable sized array may not be
initialised. Then just try this.
*/
int size=5,i;
int ar[size];
for(i=0;i<size;i++)
{
ar[i]=0;
}
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";
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.
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) );