C++中把string转换成char *再转换为string出错。代码如下

#include "stdafx.h"#include "iostream"#include "String"int main(){ std::string a; a = "212121"; char *p; a.copy(p, 5, 0); *(p + 5) = '\0'; (std::string)p; std::cout << p<<"\n"; system("pause"); return 0;}说是a.copy(p,5,0)错了,我也不知道哪里不对。

#include <iostream>
#define N 40
using namespace std;

int main(){ 
  std::string a= "212121"; 
  char p[N];//注意这里
  a.copy(p,5,0);//原*p根本没有批向任何空间,仅是一个指针。向它复制,出错。改为数组形式,分配好空间,就可以了
  *(p+5)='\0';
  cout<<p<<endl;
  char *q=p;    
  std::cout <<q<<"\n"; 
  char p2[N];
  strcpy(p2,a.c_str());//第二种方式。
  *(p2+5)='\0';
  std::cout<<p2<<endl;
  system("pause");  
  return 0;
}追问

如你所示,我尝试了一下,还是报错,错误如下。我用的是VS2017.

温馨提示:答案为网友推荐,仅供参考
第1个回答  2018-08-06
应该是你p没有开辟空间导致的。追问

我开辟空间还是错了,是不是因为新的C++标准中,safe函数修改了导致的报错。我用的VS17

追答

有可能,我是vs2013,没报错。