I convert the stringstream's string to char pointer but it writes empty string. Why does it fail?
std::stringstream ss;
ss << "de12mu";
char* msg = (char*)ss.str().c_str();
std::cout << "msg: " << msg << " " << strlen(msg) << std::endl;
I convert the stringstream's string to char pointer but it writes empty string. Why does it fail?
std::stringstream ss;
ss << "de12mu";
char* msg = (char*)ss.str().c_str();
std::cout << "msg: " << msg << " " << strlen(msg) << std::endl;
It's because your call to ss.str()
returns a temporary string, and when you then get a pointer to that temporary string it will not be valid after the statement is done.
Using that pointer after the temporary string is destroyed is undefined behavior.
Also note that the c_str
function returns const char*
.