65,186
社区成员




#include <iostream>
#include <string>
using namespace std;
int main()
{
string str("IamSpierman");
cout << str << endl;
string substr = str.substr(1);
cout << substr << endl;
const char* result = (str.substr(1)).c_str();
cout <<"\nresult == "<< result << endl;
}
const char * result =new char[substr,size()+1];
strcpy(result,substr.c_str());
cout<< result<<endl;
delete result;
string substr = str.substr(1);
cout << substr << endl;
const char* result = substr.c_str();
cout <<"\nresult == "<< result << endl;
这个也错了
const char* result = substr.c_str();这行之后 result也不一定有效
这样才正确
cout <<"\nresult == "<< substr.c_str()<< endl;
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str("IamSpierman");
cout << str << endl;
string substr = str.substr(1);
cout << substr << endl;
const char* result = (str.substr(1)).c_str();
/*猜想可能是由于result只是一个指针,没有分配空间,而(str.substr(1))只是一个临时数值,在赋值语句之后就释放掉了。
可以将(str.substr(1)).c_str()改为 substr.c_str()或者是
char result[64] = { 0 };
strcpy(result , str.substr(1).c_str());
*/
cout <<"\nresult == "<< result << endl;
}