C++ string类成员函数c_str()的用法

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!
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值