tags:

views:

50

answers:

3

hello, can somebody explain why do I receive this error, when I do:

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

thanks in advance

A: 

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 (n*m*sizeof(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.

Pavel Radzivilovsky
one more question, why do I receive an error invalid use of array with unspecified bounds?printf("%d", board[i][j]);
helloWorld
-1 C99 allows for dynamic allocation in the stack as the user code (excluding the initialization). There is no need to perform dynamic allocations.
David Rodríguez - dribeas
@helloWorld because array dimensions have to be known.
Pavel Radzivilovsky
+3  A: 

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) );
David Rodríguez - dribeas
@David Rodríguez - dribeas: I can use for this purpose malloc as well, what about the second question, I wrote it after Pavel's reply
helloWorld
@helloWorld: With stack allocated arrays, `printf( "%d", boardAux[1][2] )` compiles fine. The compiler knows the sizes and knows in what position in memory the (1,2)-th element is. If you use dynamic allocation the array is uni-dimensional and you must perform the math yourself: `printf("%d", boardAux[ 1*length + 2 ])`
David Rodríguez - dribeas
@AndreyT: Thanks for pointing the error in the `memset` call out. I have just corrected it.
David Rodríguez - dribeas
+2  A: 

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.

AndreyT
@AndreyT: where did You find this, can You give me a link?
helloWorld
@helloWorld: This is from the language standard (C99). You can get a "working" copy with TC3 updates here http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1256.pdf
AndreyT
There are subjects for which some will always disbelieve you if you only provide the informal explanation. Variable length arrays are one of these topics. +1 for quoting the standard.
Pascal Cuoq