[英]const char * pointing to same memory location
我正在尝试使用以下代码将字符串分解为整数和字符。 在立即打印的第一部分中,我得到了正确的输出,但是后来却是错误的。
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
。 然后事情将按您期望的那样工作,因为字符串将一直保留到函数退出。
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.