0

Why this code doesn't run

int [] a= new int[6]; a = {1,2,3,4,5,6};

8th Feb 2017, 2:07 AM
Prakhar Agarwal
Prakhar Agarwal - avatar
4 Respuestas
+ 6
Depends on what language you are dealing with. Nonetheless, I think the error is on the second line wherein array initialization needs to be done with a loop, if array wasn't initiated during declaration. for (int i = 0; i < 6; i++) { a[i] = i + 1; }
8th Feb 2017, 2:38 AM
Hatsy Rei
Hatsy Rei - avatar
+ 2
This is because the use of curly braces to assign values to an array is an initializing syntax only. It can only be used when first creating the array just as using the "new" keyword. int [] a = new [6]; // ok // when using this initialization style // you need to assign the elements like a [0] = 1; a [1] =2; etc Or use a loop to assign int [] a = {1,2,3,4,5,6}; // ok
8th Feb 2017, 2:46 AM
ChaoticDawg
ChaoticDawg - avatar
+ 2
the error lies on the second line. The initialisation has aleeady been done on the first line, thus the second line does not work. In order to assign values, you could either do manual assignment one by one or using for loop
8th Feb 2017, 3:56 AM
Deddy Tandean
+ 1
So is dynamic initialization not possible on array
8th Feb 2017, 3:10 AM
Prakhar Agarwal
Prakhar Agarwal - avatar