错误:从'const char *'到'char *'的无效转换[-fpermissive] [英] error: invalid conversion from 'const char*' to 'char*' [-fpermissive]
问题描述
以下代码中的赋值 C = R.c_str();
导致G ++抛出以下错误:
The assignment C=R.c_str();
in the code below causes G++ to throw the following error:
错误:从'const char *'到'char *'的无效转换[-fpermissive]"
error: invalid conversion from 'const char*' to '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;
}
为什么这是一个错误,我该如何解决?
Why is this an error and how can I solve it?
推荐答案
代码有两个问题.导致编译问题的主要原因是将 c_str()
结果(即 const
)分配给变量 C
,即不是 const
.编译器将此标记为错误,因为否则您可以这样做:
The code has two problems. The main one, which causes a compile issue, is the assignment of c_str()
result, which is const
, to variable C
, which is not const
. The compiler tags this as an error, because otherwise you could do this:
C=R.c_str();
C[2] = 'c';
这将写入内存中的只读区域,从而导致未定义的行为.
which would write to a read-only area in memory, causing undefined behavior.
您可以通过两种方式对其进行修复:
You can fix it in two ways:
- 声明
C
一个const
,即const char * C = ...
或 - 将内容复制到分配的空间中.
第一种方法很简单-您可以这样做:
The first approach is simple - you do this:
const char *C = R.c_str();
第二种方法是这样的:
char *C = new char[R.size()+1];
std::strcpy(C, R.c_str());
第二个问题是内存泄漏:您的代码将 new
的结果分配给 C
,但从不删除它.如果使用 strcpy
方法,则需要添加
The second problem is a memory leak: your code assigns C
a result of new
, but never deletes it. If you use strcpy
approach, you need to add
delete[] C;
在程序结尾,一旦使用变量 C
完成.
at the end of your program, once you are done using variable C
.
这篇关于错误:从'const char *'到'char *'的无效转换[-fpermissive]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!