0

I can do this without issue:

const char* foo = "This is a bare-string";

What I want is to be able to do the same thing with an array:

const int* bar = {1, 2, 3};

Obviously that code doesn't compile, but is there some kind of array equivalent to the bare-string?

Jonathan Mee
  • 37,899
  • 23
  • 129
  • 288

1 Answers1

1

You can't do this:

const int* bar = {1, 2, 3};

But you can do this:

const int bar[] = {1, 2, 3};

Reason is that char* in C (or C++) have an added functionality, besides working as a char pointer, it also works as a "C string", thus the added initialization method (special for char*):

const char* foo = "This is bare-string";

Best.

Aymar Fisherman
  • 388
  • 1
  • 8
  • Perhaps you can elaborate? Is a "C String" some kind of hidden special object? Note that you can't do this in C++ either: `const char* foo = {'T', 'h', 'i', 's'};` – Jonathan Mee Apr 01 '15 at 16:38
  • C string is the same as char*, it's not a hidden special object. C string is what you get when you call .c_str() from a std::string. The only difference is that char* (or C string) have a this special initialization, you can't find an analogous version of this initialization in int* for instance. It's like doing: `char foo[] = {'S', 't', 'r', 'i', 'n', 'g'}; char* bar = &foo;` In a single, more readable way: `char* bar = "String";` – Aymar Fisherman Apr 01 '15 at 17:11
  • Maybe the equivalent version would be something like: `int foo[] = {1, 2, 3}; int* bar = &foo;` But then you don't have the "abbreviated" version: `int* bar = "123"; O.O` – Aymar Fisherman Apr 01 '15 at 17:34
  • So it sounds like the answer is, there isn't a way to do this, I'd have to use `int foo[] = {1, 2, 3};` – Jonathan Mee Apr 01 '15 at 18:14