0
#include <iostream>
#include <cstring>
using namespace std;
const char * substringAfterLast(const char * str, const char * separator)
{
if (str == NULL) {
return NULL;
}
else if (str[0] == '\0' || separator == NULL || separator[0] == '\0') {
return "";
}
else {
string ret(str);
size_t found = ret.find_last_of(separator);
ret = ret.substr(found + 1);
cout << "before value = [" << const_cast<char*>(ret.c_str()) << "]" << endl;
return const_cast<char*>(ret.c_str());
}
}
int main(void)
{
cout << "after value = [" << substringAfterLast("abc", "a") << "]" << endl;
}
before value = [bc]
after value = [**gabage value**]
是否值從內存在函數的結束而消失? 我不明白爲什麼這些值會改變。
請看這裏:https://stackoverflow.com/questions/6456359/what-is-stdstringc-str-lifetime – meowgoesthedog