Initializing a dynamically allocated array.

Jul 20, 2015 at 1:50am
Greetings. The code below gives a couple of error messages that have me puzzled.

1
2
3
4
int main()
{
    int* ptr = new int[] {0,1,2,3,4};
}


the errors are
||=== Build: Debug in PPP1 (compiler: GNU GCC Compiler) ===|
error: expected primary-expression before ']' token|
error: too many initializers for 'int [1]'|

when I change the code as below the errors go away

1
2
3
4
int main()
{
    int* ptr = new int[5] {0,1,2,3,4};
}


what gives. The book I am reading (Stroustrop) says that the number of elements can be left out when an initializer list is supplied.
Jul 20, 2015 at 5:23am
> The book I am reading (Stroustrop) says that the number of elements can be left out
> when an initializer list is supplied.

The number of elements may be omitted in the definition of an array object
int a[] {0,1,2,3,4};

But it can't be omitted in a new expression.
Topic archived. No new replies allowed.