关于C++ string的c_str函数
先看代码(代码非本人所写,不知出处,侵删):
#include <iostream>
#include <string>
using namespace std;
int main(){
string s = "abc";
const char* p = s.c_str();
cout << p << endl; // 输出:abc
s = "xyz";
cout << p << endl; // 输出:xyz
return 0;
}
原因:
其实 c_str 函数返回的是指向字符串第一个字符
即:p 的值是 s[0] 的地址,应该是这样的 p=&s[0];
通过vs的快速监视有以下结果:
我们发现是一样的。
写在最后
以上都是我的猜测,有错请指正。