C compilation error: "Variable size object cannot be initialized"

Why am I getting the error message "A variable size object cannot be initialized" with the following code?

int boardAux[length][length] = {{0}}; 
+65
c compiler-errors initializer-list variable-length-array
Jun 21 '10 at 7:52
source share
8 answers

I assume that you are using the C99 compiler (with support for arrays with dynamic size). The problem in your code is that at the moment when the compilers see your variable declaration, it cannot know how many elements are in the array (I also assume here, from the compiler error, that length not a compile-time constant)

You must manually initialize this array:

 int boardAux[length][length]; memset( boardAux, 0, length*length*sizeof(int) ); 
+75
Jun 21 2018-10-10T00:
source share

You get this error because in C you are not allowed to use initializers with variable length arrays. The error message you get basically says everything.

6.7.8 Initialization

...

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

+19
Jun 21 '10 at 8:09
source share

This gives an error:

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

This also gives an error:

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

But this works great:

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

You need to put the value as follows:

 str[0]='a'; str[1]='b'; //like that; and not like str="ab"; 
+9
Nov 08 '14 at 9:21
source share

After declaring an array

 int boardAux[length][length]; 

The easiest way to set the initial values ​​as zero is to use for the loop, even if it can be a little long

 int i, j; for (i = 0; i<length; i++) { for (j = 0; j<length; j++) boardAux[i][j] = 0; } 
+1
Mar 27 '16 at 12:35
source share

Just declare the length minus, if that is not the case, you should allocate memory dynamically.

0
Mar 02 '16 at 20:26
source share

For a separate declaration and initialization of C ++.

 int a[n][m] ; a[n][m]= {0}; 
0
Sep 25 '16 at 6:09
source share

Another C ++ way:

 const int n = 5; const int m = 4; int a[n][m] = {0}; 
-one
Nov 23 '17 at 7:18
source share

You cannot do this. The C compiler cannot do such a complicated thing on the stack.

You must use heap and dynamic allocation.

What you really need to do:

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

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

-5
Jun 21. '10 at 7:55
source share



All Articles