我正在尝试使用以下代码将字符串分解为整数和字符。在关于立即打印的第一部分中,我得到了正确的输出,但后来它是错误的。
int Lottery::calcInvOdds(string ruleConstraint){
const char * sorted;
const char * unique;
string temp;
size_t pos;
temp = ruleConstraint;
pos = temp.find_first_of(" ");
sorted = temp.substr(0,pos).c_str();
cout << temp << endl;
cout << "S = " << sorted << endl;
temp = temp.substr(pos+1);
unique = temp.substr(0,pos).c_str();
cout << "U = " << unique << endl;
cout << "Sorted = " << sorted[0] << " " << "Unique = " << unique[0] << endl<<endl;
return 0;
}
输出是这样的:
T F
S = T
U = F
Sorted = F Unique = F
F T
S = F
U = T
Sorted = T Unique = T
但是在用 char sorted[2]
和 temp.substr(0,pos).c_str(); 之类的数组替换
与 const char *
之后;*temp.substr(0,pos).c_str()
,显示了正确的输出。这种行为的原因是什么?
最佳答案
sorted = temp.substr(0,pos).c_str();
这行不通。 temp.substr(0,pos)
返回一个临时的string
,.c_str()
得到一个指向其内容的指针,语句完成后临时 string
被释放,使 sorted
指向释放的内存。
您最好的选择是甚至不去转换为 const char*
而是将 sorted
和 unique
更改为 string
s。然后事情会像您预期的那样工作,因为字符串将一直存在直到函数退出。
int Lottery::calcInvOdds(const string& ruleConstraint){
size_t pos = ruleConstraint.find_first_of(" ");
string sorted = ruleConstraint.substr(0, pos);
// The above line could be rewritten as:
// string sorted(ruleConstraint, 0, pos);
cout << ruleConstraint << endl;
cout << "S = " << sorted << endl;
// -- Not sure this is what you want, but it's what your code does.
#if 1
string unique = ruleConstraint.substr(pos + 1, pos);
// -- maybe you meant this
#else
size_t pos2 = ruleConstraint.find_first_of(" ", pos + 1);
string unique(ruleConstraint, pos + 1, pos2 - pos - 1);
#endif
cout << "U = " << unique << endl;
cout << "Sorted = " << sorted[0] << " " << "Unique = " << unique[0] << endl << endl;
return 0;
}
关于c++ - const char * 指向同一内存位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24421831/