# [C++]Array of strings

## Recommended Posts

Gumgo    968
I want an array of 5 std::strings. I tried declaring like this: std::string str[5]; However my program is crashing when I try to access them: str[...].length(); The debugger says that there is apparently not an array of strings but it looks like only 1. What is the correct way of doing this? Thanks.

##### Share on other sites
dave    2187
std::vector< std::string > ftw!

##### Share on other sites
Gumgo    968
I can't seem to get that working either. I've tried both of these:
struct ConvComponent{	BYTE type;	std::vector <std::string> str;	BYTE val[5];	ConvComponent();};ConvComponent::ConvComponent(){	for (int i = 0; i < 5; i++)		str.push_back( "" );}andstruct ConvComponent{	BYTE type;	std::string str[5];	BYTE val[5];};

In neither case, referring to the string: str[...] seems to work.

##### Share on other sites
rip-off    10976
I'm guessing you have more serious problems then. Are you allocating the ConvComponent by itself, or is it a member of some other class? If this is the case, is the "this" pointer of the calling function valid? If you have a pointer to a ConvComponent instance, is the pointer valid?

I would assume a minimal program works fine:
// Given that the array "val" has 5 elements// Do you need a BYTE per std::string?// Should you be using a vector of {byte, std::string} pairs?struct ConvComponent{	BYTE type;	std::vector <std::string> str;	BYTE val[5];	ConvComponent();};// This is the same as the loop version// It default constructs 5 strings in the vector// A default constructed string is the same as one// initialised like std::string("");ConvComponent::ConvComponent():   str(5){}int main(){    ConvComponent component;    // do stuff with component}

By reducing the set of things like this, you can rule out a lot of things. Once the above works, slowly start introducing any additional classes etc until it breaks. Then figure out what you are doing wrong with that part [smile]

##### Share on other sites
Gumgo    968
Hmm you're right... it is something more complicated (ConvComponent is in a vector, something is wrong with that it seems). Anyway debugging time...

##### Share on other sites
3ndo    100
Please note that the STL string uses an overloaded subscript [i] to access the character at position i. Have you tried just creating 5 pointers to strings and instantiating them in the constructor?

##### Share on other sites
superpig    1825
What kind of crash do you get? My article may help you.