码迷,mamicode.com
首页 > 其他好文 > 详细

C string类c_str() 详解

时间:2015-02-06 13:17:21      阅读:183      评论:0      收藏:0      [点我收藏+]

标签:c

c_str() 返回以最后一个指向null结束。

#include <iostream>
using  namespace  std;
int  main(int argc, char *argv[])
{
    const char *ch;
    string s = "abcdef";
    ch = s.c_str();
    cout<<ch<<endl;
    s = "56789";
    cout<<ch<<endl;
    return 0;
}

[root@pprobe23 ~]$ ./a.out
abcdef
56789

可看出ch改变了,这样使用不安全。最好的使用途径是 strcpy。

#include <iostream>
#include <string.h>
using  namespace  std;
int  main(int argc, char *argv[])
{
    char *nch = new char[20];
    const char *ch;
    string s = "abcdef";
    strcpy(nch,s.c_str());
    cout<<nch<<endl;
    s = "56789";
    cout<<nch<<endl;
    return 0;
}

[root@pprobe23 ~]$ ./a.out
abcdef
abcdef

只有这样使用更安全。

C string类c_str() 详解

标签:c

原文地址:http://blog.csdn.net/zhangxxxww/article/details/43562481

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!