I have the following C++ code:
#include <string>
#include <iostream>
int main(int argc, char** argv)
{
int size;
std::string strArray[3];
std::string str0 = "String 0";
std::string str1 = "String 1";
std::string str2 = "String 2";
strArray[0] = str0;
strArray[1] = str1;
strArray[2] = str2;
for (int i = 0; i < 3; i++)
{
std::cout << strArray[i] << std::endl;
}
str1.resize(200, 'a');
for (int i = 0; i < 3; i++)
{
std::cout << strArray[i] << std::endl;
}
std::cout << str1 << std::endl;
std::cin.get();
return 0;
}
The idea here is that I have an array which is a contiguous block of memory, where each member is a std::string, which are mutable and therefore variable in size. I expected this code to break since I resize str1 to take up loads more space than original, and therefore "overflowing" into str2.
Instead I get this output:
String0
String1
String2
String0
String1
String2
String1aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa...
I have two questions about this. First of all, how is it that increasing the size of str1 and adding loads of characters to it does not flow over into str2 even though they should be in a contiguous block of memory?
Second, how come when I print the array for the second time after resizing str1 AND add the characters to it it still prints the original str1? I have a feeling that this will have something to do with the answer to my first question but I can't quite see what is going on here.