In C++ Primer 5th Edition, it says:
The Array returned by c_str is not guaranteed to be valid indefinitely.
So I did a test:
// c_str exploration
std::string strTest = "This is a test";
const char* s1 = strTest.c_str();
strTest = "This is b test";
std::cout << s1 << std::endl;
Since s1 is a pointer, it definitely shows the new value. However when I change the value to a string of different length, it usually shows some garbage:
// c_str exploration
std::string strTest = "This is a test";
const char* s1 = strTest.c_str();
strTest = "This is b testsssssssssssssssssssssssssss";
std::cout << s1 << std::endl;
I figured that it is because the returned C String already fixed the position of the ending null character, so when the length changes it invalidate everything. To my surprise, sometimes it is still valid even after I change the string to a new length:
// c_str exploration
std::string strTest = "This is a test";
const char* s1 = strTest.c_str();
strTest = "This is b tests"; // Note the extra s at the end
std::cout << s1 << std::endl;
Second question:
I'm also not sure why std::cout << s1
prints the content instead of the address of the C String. While the following code prints the address of the Integer as I expected:
int dim = 42;
int* pdim = &dim;
std::cout << pdim << std::endl;
This prints out the character 'T', as expected:
std::cout << *s1 << std::endl;
My assumption is that std::cout does an auto convert, but please lecture me more on this.