Initializing variable length array

haccks picture haccks · Jun 27, 2013 · Viewed 54.6k times · Source

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};

?

Answer

Carl Norum picture Carl Norum · Jun 27, 2013

You'll have to use memset:

memset(board, 0, sizeof board);