将string str中的str转换成字符数组

#include <iostream>
#include <map>
#include <string.h>

using namespace std;

int main()
{
    /*下面做法错误
    char* c;
    string s="1234";
    c = s.c_str(); //c最后指向的内容是垃圾,因为s对象被析构,其内容被处理
    */
    string str;
    cin >> str; cout << "____"<<endl;
    char *p=new char[str.size()+1];
    strcpy(p,str.c_str()); //c_str 取得C风格的const char* 字符串
    cout <<p<<endl;
    cout <<str.c_str()<<endl;

    p[0]='w';
    cout <<p<<endl;
    cout <<*(++p)<<endl;//p是个指针变量
    return 0;
}

 


  

posted on 2017-07-23 16:08  多情剑客无情剑;  阅读(348)  评论(0)    收藏  举报

导航