I have a function that is returning a string. However, when I call it and do c_str()
on it to convert it into a const char*
, it only works when I store it into another string first. If I directly call c_str()
off of the function, it stores garbage value in the const char*
.
Why is this happening? Feel like I'm missing something very fundamental here...
string str = SomeFunction();
const char* strConverted = str.c_str(); // strConverted stores the value of the string properly
const char* charArray= SomeFunction().c_str(); // charArray stores garbage value
static string SomeFunction()
{
string str;
// does some string stuff
return str;
}
;
the object gets deleted, and presto: you get garbage.