下面代码中的赋值 C=R.c_str();
会导致 G++ 抛出以下错误:
错误:从 ‘const char*’ 到 ‘char*’ 的无效转换 [-fpermissive]“
#include <iostream>
#include <string>
using namespace std;
int main()
{
string R = "killme";
char *C = new char[100];
C=R.c_str();
cout<<*C;
}
为什么这是一个错误,我该如何解决?
原文由 Roy Dai 发布,翻译遵循 CC BY-SA 4.0 许可协议
代码有两个问题。 The main one, which causes a compile issue, is the assignment of
c_str()
result, which isconst
, to variableC
, which is notconst
.编译器将此标记为错误,否则您可以这样做:这将写入内存中的只读区域,导致未定义的行为。
您可以通过两种方式修复它:
C
aconst
,即const char *C = ...
,或第一种方法很简单 - 你这样做:
第二种方法是这样工作的:
第二个问题是内存泄漏:您的代码分配了
C
的结果new
,但从不删除它。如果你使用strcpy
方法,你需要添加在程序结束时,一旦使用变量
C
完成。