Array initialization when using the new

In C #, I could do this:

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

But can I do something similar in C ++? I tried:

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

But it does not compile.

+5
source share
6 answers

This is a mistake in the C ++ specification (which prevents this simple construct from compiling). You need to specify 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 copy the type name, this is the type identifier, not the identifier of the new type, and therefore syntactically allows you to omit the size expression. So you can find an implementation that lets you say

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

, , ( new , ).

+6

?

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

. std::vector

+6

, ++. std::vector.

3 'a.

std::vector<char> vectorOfChars(3, 'a');

++ 11, .

std::vector<char> vectorOfChars{'a', 'a', 'a'};
+4

, :

   const char a[] = {'a', 'a', 'a'};
+3

, :

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

Arrays (C++) MSDN.

+1

string a = "aaa"; a [0], a [1]..etc , 2-D string..etc

0

All Articles