Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializing variable length array [duplicate]

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

?

like image 469
haccks Avatar asked Jun 26 '13 23:06

haccks


People also ask

How do you initialize a variable length array?

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.

How do you initialize a variable sized array to 0?

For the sake of completeness, to initialize to 0, int array[i] = { 0 }; is unbeatable for conciseness.

How do you initialize an array with variable length in Java?

In Java int[] arrays are initialized with all elements 0 by default, so no other action needs to be taken except new int[n] to create an array filled with 0. ("Then [...] a one-dimensional array is created of the specified length, and each component of the array is initialized to its default value. [...]

How do you declare an array with variable size in C++?

If you want a "variable length array" (better called a "dynamically sized array" in C++, since proper variable length arrays aren't allowed), you either have to dynamically allocate memory yourself: int n = 10; double* a = new double[n]; // Don't forget to delete [] a; when you're done!


2 Answers

You'll have to use memset:

memset(board, 0, sizeof board); 
like image 126
Carl Norum Avatar answered Nov 01 '22 18:11

Carl Norum


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.

like image 33
AnT Avatar answered Nov 01 '22 18:11

AnT