信息技术

当前位置: 主页 > 编程语言 > C/C++ >

c++中string与char*的转换

时间:2010-09-16 16:02来源:未知 作者:admin 点击:
本来是想通过strcpy将string类型转换为char*类型的.所以用如下代码: #include stdio.h #include iostream #include string using namespace std; int m

本来是想通过strcpy将string类型转换为char*类型的.所以用如下代码:
#include <stdio.h>
#include <iostream>
#include <string>
using namespace std;
int main(int argc, char* argv[])
{
string test="test";
string newdn="dcxlydcjlu";
const char * temp=test.c_str();
char * temp_2;
strcpy(temp_2,temp);
cout << temp_2 << endl;
return 0;
}
如果没有 string newdn="dcxlydcjlu";可以通过执行,如果有则出现段错误.原因在于:

string test="test";
const char * temp=test.c_str();
char * temp_2;
strcpy(temp_2,temp);
cout << temp_2 << endl;
没有为 temp_2 分配空间。

/*

 String to char[] use: String.toCharArray() 或者String.c_str()
 char[] to String use: new String(char[])
  */

(责任编辑:admin)
顶一下
(0)
0%
踩一下
(0)
0%
------分隔线----------------------------
发表评论
请自觉遵守互联网相关的政策法规,严禁发布色情、暴力、反动的言论。
评价:
表情:
用户名: 验证码:点击我更换图片
栏目列表
推荐内容