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.
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).
new should be used here at all. Use the stack or a container.why not just do this? :
char a[] = {'a', 'a', 'a'};
Also avoid using arrays completely. Use std::vector
std::vector, like "if you're lucky enough to have a compiler supporting c++11, then you can so and so."You probably don't want to use an array in C++. Use a std::vector instead.
You can even initialise it to 3 'a's.
std::vector<char> vectorOfChars(3, 'a');
If your compiler supports C++11, you can even use an initialiser list.
std::vector<char> vectorOfChars{'a', 'a', 'a'};
char a[] = {'a', 'a', 'a'};. Much easier!char *a = new char [3] {'a', 'a', 'a'};