andrewmag
andrewmag

Reputation: 262

Array of strings initialization in c++

i know i can initialize like this

std::string foo [3] = {"T1","T2","T3"};

but what if declared it before do i have to initialize each one by its own? example

std::string foo [3];
foo[0] = "T1"
foo[1] = "T2"
foo[2] = "T3"

i mean giving the string all the values at once foo ={"T1","T2","T3"}

Upvotes: 3

Views: 8645

Answers (5)

Kevin
Kevin

Reputation: 56149

No, (unlike Java), when you declare the array, it creates a string at each index using the default constructor.

Edit for clarity:

by "new" I don't mean like the new allocation to the heap, it gets stored wherever you declared it, in the data section (for globals) or stack (locals).


From a comment, it seems you're thinking more of something like this:

std::string foo[3];
...
foo = {"a","b","c"}; // DOES NOT WORK

No, you can't do that. foo already has its space allocated and initialized, and you can't just assign whole arrays like that (except in the initializer). If you declared it as std::string *foo you could, but I don't recommend that in this case.

Upvotes: 1

bitmask
bitmask

Reputation: 34714

Technically, you cannot initialise it after the declaration. The nuance is important, because in your second example you assign to the individual strings. Now, you want to assign to the whole array, which doesn't work. If you used a more intelligent data structure like std::vector you could indeed assign all values in one instruction, because the vector would throw away the old strings and create new ones that would be copy constructed from your "T1",.. strings.

Upvotes: 1

Ben Voigt
Ben Voigt

Reputation: 283961

In C++0x, you'll be able to use generalized initializer lists. But it won't be much different from writing the assignments out longhand.

Do note, however, that in the case where you had a complicated expression repeated for each assignment (as K-ballo points out, the different between assignment and initialization is sometimes important, get in the habit of distinguishing):

ALongPointerName->ALongMemberName.ALongArrayName[0] = "T1";
ALongPointerName->ALongMemberName.ALongArrayName[1] = "T2";
ALongPointerName->ALongMemberName.ALongArrayName[2] = "T3";

you can use a reference to shorten that up:

auto& a = ALongPointerName->ALongMemberName.ALongArrayName;
a[0] = "T1";
a[1] = "T2";
a[2] = "T3";

which takes away much of the pain.

Upvotes: 0

user969416
user969416

Reputation:

I'm still learning C++ and I'm not very experienced, but I believe that is perhaps the best way if you wanted to initialize after the declaration. Or you could use a for loop for example to populate it.

Upvotes: 0

K-ballo
K-ballo

Reputation: 81409

what if declared it before do i have to initialize each one by its own?

You are not initializing each one by its own. They are initialized to the empty string (default constructed), and you are then assigning values to them.

Upvotes: 1

Related Questions