Conversion from int to c-string (const char *) fails
I cannot convert int
to c-string ( const char*
):
int filenameIndex = 1;
stringstream temp_str;
temp_str<<(fileNameIndex);
const char* cstr2 = temp_str.str().c_str();
There is no error, but cstr2
does not receive the expected value. It is initialized with some address.
What is wrong and how can I fix it?
source to share
temp_str.str()
returns a temporary object that was destroyed at the end of the statement. Thus, the address it points cstr2
to becomes invalid.
Use instead:
int filenameIndex = 1;
stringstream temp_str;
temp_str<<(filenameIndex);
std::string str = temp_str.str();
const char* cstr2 = str.c_str();
source to share
temp_str.str()
- the temporary value string
destroyed at the end of the instruction. cstr2
is a dangling pointer, invalid when the array it pointed to was deleted by destroying the string.
You will need a non-temporary string if you want to store a pointer to it:
string str = temp_str().str(); // lives as long as the current block
const char* cstr2 = str.c_str(); // valid as long as "str" lives
Modern C ++ also has slightly more convenient string conversion functions:
string str = std::to_string(fileNameIndex);
const char* cstr2 = str.c_str(); // if you really want a C-style pointer
Again, this returns value string
by value, so don't trycstr2 = to_string(...).c_str()
source to share