int main() {
string str[5] = "ABCD";
std::cout << str[3] << std::endl;
std::cout << str[0] << std::endl;
return 0;
}
This code prints:
ABCD
ABCD
I didn't get it, how str[3] prints ABCD?
Compiler: GCC 6.3
On
You can try this to get your code compile:
string str[5] = {"ABCD", "", "", "", ""};
str[3] in your code means 4the string of the array if you get it compiled.
But you most likely meant to have:
char str[5] = "ABCD";
string and char are not the same thing. If you want to access single char in a string you don’t need an array of strings. A single string is all you need:
string str = "ABCD";
std::cout << str[3] << std::endl;
On
What's happening is:
the line string str[5] = "ABCD"; is simply copying/initializing all the indexes of variable str with the value ABCD like str[0] = "ABCD", str[1] = "ABCD", and so on.
So, when you run std::cout << str[3] << std::endl; and std::cout << str[0] << std::endl;, you're getting the value from the respective index of the string array str.
The code is not valid C++ code and it shouldn't compile. And it doesn't with clang and gcc version above 7. It is most likely a bug in older version of gcc that got fixed in version 7.
What you have here is a C array of 5 elements of
std::string. This is how you would initialize it:In this case
strings[0]would be"1st string"andstrings[3]would be"4th string".However don't do this. Don't use C arrays in C++. Use
std::vectororstd::arrayif you need an array of strings:std::array<std::string> stringsorstd::vector<std::string> strings.That being said, I suspect that you want just one string, aka:
In this case
str[0]is'A'andstr[3]is'D'