21

在初始化可变长度数组时,编译器会给出错误消息:

[Error] variable-sized object may not be initialized  

代码片段:

int n; 
printf("Enter size of magic square: ");
scanf("%d",&n);

int board[n][n] = {0};

可变长度数组应该如何初始化?以及为什么它的所有元素都没有0按照下面给出的方式初始化;

   int board[n][n];
   board[n][n] = {0};

?

4

3 回答 3

25

你必须使用memset

memset(board, 0, sizeof board);
于 2013-06-26T23:55:52.937 回答
19

VLAs cannot be initialized by any form of initialization syntax. You have to assign the initial values to your array elements after the declaration in whichever way you prefer.

C11: 6.7.9 Initialization (p2 and p3):

No initializer shall attempt to provide a value for an object not contained within the entity being initialized.

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

于 2013-06-27T00:02:04.830 回答
0

1.您可以简单地初始化数组如下 -

int n; 
printf("Enter size of magic square: ");
scanf("%d",&n);

int board[n][n];
for(int i=0; i<n; i++)
   for(int j=0; j<n; j++)
   {
      board[i][j] = 0;
   }
}

2. memset()应该只在你想将数组设置为“0”时使用。

于 2013-12-24T15:05:05.443 回答