C语言 初始化变长数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17332360/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 06:49:18  来源:igfitidea点击:

Initializing variable length array

cvariable-length-arrayarray-initialization

提问by haccks

On initializing a Variable length array compiler gives an error message:

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

[Error] variable-sized object may not be initialized  

Code snippet:

代码片段:

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

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

How should Variable Length arraysbe initialized? And why it's all elements are not initialized to 0in the way give below;

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

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

?

?

采纳答案by AnT

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

沃拉斯不能初始化任何形式的初始化语法。您必须在声明后以您喜欢的任何方式为数组元素分配初始值。

C11: 6.7.9 Initialization (p2 and p3):

C11:6.7.9 初始化(p2 和 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.

任何初始化程序都不应尝试为未包含在正在初始化的实体中的对象提供值。

要初始化的实体的类型应该是一个未知大小的数组或一个不是可变长度数组类型的完整对象类型

回答by Carl Norum

You'll have to use memset:

你必须使用memset

memset(board, 0, sizeof board);

回答by Parag Gangil

1.You can simply initialize the array as follows-

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()should only be used when you want to set the array to "0".

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