So I would just like to create an array of C-strings in C++. Yes, I know that C++ uses the string data type, but what I'm working on requires me to make an array of C-strings. C-strings themselves are an array of chars. So would making an array of C-strings be just like making a two-dimensional char array? And then to access each individual char I would need to specify its respective row and column position. However, I would like to imagine this as a single-dimensional array of C-strings, where every index returns a complete C-string. How can I do that? Please explain. How do I loop through such an array and print out or return every C-string instead of having nested loops to return every char separately?
2 Answers
For string literals you can just do this:
const char *strings[] = { "foo", "bar", "blech" };
For an array of strings you want to modify you might do something more like this:
char strings[3][80] = { "foo", "bar", "blech" };
Either way you can just print them like this:
for (int i = 0; i < 3; ++i)
{
std::cout << strings[i] << std::endl;
}
or perhaps more idiomatically:
for (auto & s : strings)
{
std::cout << s << std::endl;
}
Comments
A C-style string is nothing more than, basically, an array of char, terminated with a '\0'. To have an array of "strings" you simply have an array of arrays, like
char my_array_of_strings[ARRAY_SIZE][STRING_SIZE + 1]; // +1 for terminator
Or you could have an array of pointers:
char* my_array_of_strings[ARRAY_SIZE];
Which one is best depends on your use-cases.