5

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.

2
  • 1
    Try char a[] = {'a', 'a', 'a'};. Much easier! Commented Feb 10, 2013 at 17:12
  • 1
    Specify the size: char *a = new char [3] {'a', 'a', 'a'}; Commented Feb 10, 2013 at 17:13

6 Answers 6

6

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).

Sign up to request clarification or add additional context in comments.

3 Comments

I don't think new should be used here at all. Use the stack or a container.
@inverse you should add that to the question as a comment. i do not recommend anything in my answer. i just fixed his syntax.
all the replies that talk about stack arrays or vectors do not really answer his question about the syntax of new.
6

why not just do this? :

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

Also avoid using arrays completely. Use std::vector

2 Comments

It would be great to add something on initializers for std::vector, like "if you're lucky enough to have a compiler supporting c++11, then you can so and so."
@AntonKovalenko I am not current on C++11, my focus has shifted to C#. But I would not mind if you want to add something to the answer :-)
4

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'};

Comments

3

I think what you want is this:

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

Comments

1

Yes, you can do it like;

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

Check out Arrays (C++) from MSDN.

Comments

0

string a = "aaa"; a[0] , a[1] ..etc This will be much easier if you wanna make 2-D arrays of string..etc

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.