C++ string类成员函数c_str()的用法
c_str()
生成一个const char*
指针,指向以空字符终止的数组,该指针不需要手动释放和删除。
在使用c_str()
时要注意,c_str()
指向的数组是一个临时数组,其中的数据会因为程序的某些操作而失效,例如:
string str("hello!");
const char *pstr = str.c_str();
cout << pstr << endl; // hello!
str = "world";
cout << pstr << endl; // world
这是因为c_str()
返回的指针指向的空间内容被改变,再对该指针进行操作是不可行的,此时就需要使用strcpy()
等函数对该临时空间中的数据进行拷贝,才不会在后续使用中出错。
string str("hello!");
char *pstr = new char[10];
strcpy( pstr, str.c_str() );
cout << pstr << endl; // hello!
str = "world";
cout << pstr << endl; // hello!