Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inline array initialization

Tags:

c++

arrays

c++11

I was used to using

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

for initializing array. But it seems nowadays, this does not work anymore, i have to explicitly state how many elements there are, with

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

so compilers forgot how to count ?

And to make this a closed question, is there a way to omit the number of elements ?

like image 330
Gzorg Avatar asked Jan 03 '11 10:01

Gzorg


People also ask

How can we initialize an array?

The initializer for an array is a comma-separated list of constant expressions enclosed in braces ( { } ). The initializer is preceded by an equal sign ( = ). You do not need to initialize all elements in an array.

How do you initialize an array in C++?

Initializing arrays But the elements in an array can be explicitly initialized to specific values when it is declared, by enclosing those initial values in braces {}. For example: int foo [5] = { 16, 2, 77, 40, 12071 };

How do you initialize an array in Java with 0?

Using default values in initialization of array For double or float , the default value is 0.0 , and the default value is null for string. Type[] arr = new Type[capacity]; For example, the following code creates a primitive integer array of size 5 . The array will be auto-initialized with a default value of 0 .


2 Answers

This has never worked in the current version of C++, you have only been able to zero-initialize (or not initialize) dynamically allocated arrays.

What has always worked is non-dynamically allocated array initialization:

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

Perhaps you are confusing it with this?

Even in C++0x it is not legal syntax to omit the explicit array size specifier in a new expression.

like image 66
CB Bailey Avatar answered Oct 02 '22 18:10

CB Bailey


C++ have never allowed to initialize array with an unknown size of elements like above. The only 2 ways I know, is specify the number of elements or use pointers.

like image 37
Oleg Danu Avatar answered Oct 02 '22 20:10

Oleg Danu