Is it possible to initialize an array of x length assigning values in C ++?


I would like to know if it is possible to initialize an array by assigning values. Is the only way iterating with a for ?

Something that is very easy in Javascript is to declare a variable assigning values, and also has the advantage that it is not necessary to indicate the length of the array, in comparison with C ++ .

var array=[1,2,3,4,5]

If I do I put the 5 in the brackets in C ++ , I have no problem, compile and everything:

int array_enteros[5]={1,2,3,4,5};

But when I do the following:

int 5;
int array_enteros[digitos]={1,2,3,4,5};

The CodeBlocks throws me an error:


Warning: extended initializer lists only available with -std = c ++ 11 or -std = gnu ++ 11 [enabled by default]


error: assigning to an array from an initializer list


error: variable-sized object 'array_enteros' may not be initialized

What I would like to do is declare an array but indicating the length by a variable, or if possible, it would be much better not to use the variable, and change the length automatically depending on the number of values that I give assign.

asked by ArtEze 28.05.2017 в 23:21

2 answers


If what you want is that the array has the length equal to the number of values that the array has, without having to declare it you can leave the square brackets [] empty and C ++ will automatically assume the size of the array with the values that you You have indicated.


int array_enteros[]={0,1,2,3,4,5};

From the documentation :


When an initialization of values is provided for an array, C ++ allows the possibility of leaving the square brackets empty [] . In this case, the compiler will assume automatically to size for the array that matches the number of values included between the braces {} :


int foo [] = { 16, 2, 77, 40, 12071 };

In Spanish it would be:


When initializing values to the array is provided, C ++ allows you to leave empty brackets [] . In this case, the compiler automatically assumes the size of the array, which matches the number of values included between braces {} .

answered by 28.05.2017 / 23:34

Like when you create a for you need to declare the variable first and initialize it:

for(int i=0;i<=5;i++)

You can declare a variable:

int mi_variable=5

... and the array:

int mi_array[mi_variable]

The array takes the value of% co_of% that is 5.

answered by 28.05.2017 в 23:45