开发者

C declaring a 2d array using constants

I have a header file for a game that declares a 2d array for a board.

#ifndef GAME_H_
#de开发者_开发百科fine GAME_H_

static const int columns = 15;
static const int rows = 15;

int board[rows][columns];

#endif /* GAME_H_ */

I get an error "error: variably modified 'board' at file scope".


C doesn't allow const variables as array bounds. Use an enum instead:

enum { columns = 15, rows = 15 };


That expression is not allowed, it can be used in C++, the only way around this is to define it like this:

#ifndef GAME_H_
#define GAME_H_

#define COLUMNS 15
#define ROWS 15

int board[ROWS][COLUMNS];

#endif /* GAME_H_ */


As of C99, you can declare what is known as a variable length array (VLA) where the size of the array dimension is a non-constant expression; IOW, you can do this:

int foo()
{
  int x = 5;
  int y = 10;
  int values[x][y];
  ...
}

Note that this is only true for C99; C89 and earlier requires you to use compile-time constant expressions for the array dimension.

The problem with VLAs is that, because of how they work, they may only be declared at block scope (that is, within a function or a compound statement in the function); they may not be declared as static or extern, and they may not be declared at file scope (which is the source of your particular error message).

In this particular case, you will need to use compile-time constant expressions (which const-qualified variables are not):

#define COLUMNS 15
#define ROWS    15

extern int board[ROWS][COLUMNS];

Note the addition of the extern keyword in the array declaration. You don't want the declaration in the header file to be the defining declaration for the array; instead, put the defining declaration in the source file that actually implements the game board. Otherwise every source file that includes that header will try to create its own definition for board and it will be up to the linker to sort it all out.


int board[rows][columns];

is not valid C. You can only define an array with a constant, not with a variable reference. Even if the variable reference refers to a value that is constant, rows and columns are references to the constant values an not the constant values themselves.

There are a number of ways to get this to work as you want:

  1. You could define the "variables" in the preprocessor, so they get flattened into constants just before compile time.
  2. You could define the values as part of an enumeration enum as the C compiler's rules for enumerations is to automatically covert them to their constant values whenever a type mismatch is detected.


Try this

See if the above link helps you out any.


array declarations need a constant value before compilation. You can #define variables in it or use pointers to make it work like an array. Both ways are fine will give you same results and simplicity.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜