c++ - const char * 指向同一内存位置

标签 c++

我正在尝试使用以下代码将字符串分解为整数和字符。在关于立即打印的第一部分中,我得到了正确的输出,但后来它是错误的。

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* 而是将 sortedunique 更改为 strings。然后事情会像您预期的那样工作,因为字符串将一直存在直到函数退出。

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/

相关文章:

c++ - 找到多重定义的符号?

c++ - 指向另一个类的方法的指针

C++ 搜索文件名指向字符串 strcmp 错误的指针

c++ - C++中 vector vector 中索引的最有效排序

c++ - 几个直方图的平均直方图

c++ - 如何链接 .h 文件中声明为 extern 的函数来创建 .dll 文件?

c++ - Boost.Spirit.X3如何防止token被之前的规则解析?

c++ - pow(x, 0.5f) 的快速实现是否比快速 sqrt(x) 更快?

c++ - 捕获参数是从右值 lambda 复制的吗?

c++ - 用于在 Windows 上捕获声音的 API