Initializing variable length array [duplicate]

断了今生、忘了曾经 提交于 2019-12-17 02:37:46

问题


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 arrays be initialized? And why it's all elements are not initialized to 0 in the way give below;

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

?


回答1:


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.




回答2:


You'll have to use memset:

memset(board, 0, sizeof board);



回答3:


1.You can simply initialize the array as follows-

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".



来源:https://stackoverflow.com/questions/17332360/initializing-variable-length-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!