Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array initialization when using new

In C# I could do this:

char[] a = new char[] {'a', 'a', 'a'};

But can I do something like that in C++? I tried:

char *a = new char [] {'a', 'a', 'a'};

But it doesn't compile.

like image 885
nhtrnm Avatar asked Feb 10 '13 17:02

nhtrnm


2 Answers

This is a bug in the C++ spec (which doesn't let this simple construct to compile). You need to supply the size

char *a = new char [3] {'a', 'a', 'a'};

See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1469 . Note that if you parenthesize the type name it is a type-id and not a new-type-id and hence syntactically allows you to omit the size expression. So you may be able to find an implementation that allows you to say

char *a = new (char[]){'a', 'a', 'a'};

Althought it is clear that it wasn't the explicit intent that this is possible (and some rules in the new paragraphs can be interpreted to forbid it).

like image 152
Johannes Schaub - litb Avatar answered Sep 30 '22 17:09

Johannes Schaub - litb


why not just do this? :

char a[] = {'a', 'a', 'a'};

Also avoid using arrays completely. Use std::vector

like image 21
Aniket Inge Avatar answered Sep 30 '22 18:09

Aniket Inge