类型为“ const char *”的值是不能用于初始化类型为“ char *”的实体 [英] A value of type "const char*" cannot be used to initialize an entity of type "char *"
问题描述
我有这样的代码,但我不断收到此错误:
I have a code like this but I keep receiving this error :
A value of type "const char*" cannot be used to initialize an entity of type "char *"
发生了什么?< br>
我已经阅读了以下线程,但没有看到任何答案,因为它们都是 char
到 char *
或 char *
到 char
:
值类型const char不能用于初始化char *类型的实体*
类型为char *的值不能用于初始化类型为 char的实体
What is going on?
I have read up on the following threads but have not been able to see any result to my answer as all of them are either from char
to char*
or char*
to char
:
Value type const char cannot be used to initialize an entity of type char*
Value of type char* cannot be used to initialize an entity of type "char"
#include <iostream>;
using namespace std;
int main() {
int x = 0; //variable x created
int cars (14);//cars is created as a variable with value 14
int debt{ -1000 };//debt created with value 1000
float cash = 2.32;
double credit = 32.32;
char a = 'a';//for char you must use a single quote and not double
char* sandwich = "ham";
return 0;
}
我正在使用Visual Studio Community 2017
I am using Visual Studio Community 2017
推荐答案
那是正确的。假设您有以下代码:
That is correct. Let’s say you had the following code:
const char hello[] = "hello, world!";
char* jello = hello; // Not allowed, because:
jello[0] = 'J'; // Undefined behavior!
哇! const char *
是指向 const char
的非常量指针。如果将其值分配给非常量 char *
,则会丢失其 const
属性。
Whoops! A const char*
is a non-const pointer to const char
. If you assign its value to a non-const char*
, you’ve lost its const
property.
A const
指向非常量 char $ c的指针$ c>将是一个
char * const
,如果需要,您可以整天初始化一个 char *
。
A const
pointer to non-const char
would be a char* const
, and you can initialize a char*
from that all day if you want.
如果确实需要,可以使用 const_cast< char *>(p)
实现,和我偶尔会有,但这通常是严重的设计缺陷的迹象。如果您实际上使编译器发出指令以写入以字符串常量作为别名的内存,则会出现未定义的行为。 可能可能出错的许多事情之一是,某些实现会将常量存储在只读内存中并崩溃。或者相同的内存字节可能出于多种目的而重复使用,因为毕竟,我们警告您不要更改它。
You can, if you really want, achieve this with const_cast<char*>(p)
, and I occasionally have, but it’s usually a sign of a serious design flaw. If you actually get the compiler to emit instructions to write to the memory aliased by a string constant, you get undefined behavior. One of the many things that might go wrong is that some implementations will store the constant in read-only memory and crash. Or the same bytes of memory might be re-used for more than one purpose, because after all, we warned you never to change it.
顺便说一句,规则在C中是不同的。这仅是为了与没有 const
关键字的C的早期版本向后兼容,并且永远不要编写对字符串使用非const别名的新代码。常数。
By the way, the rules in C are different. This is solely for backward-compatibility with early versions of C that did not have the const
keyword, and you should never write new code that uses a non-const alias to a string constant.
这篇关于类型为“ const char *”的值是不能用于初始化类型为“ char *”的实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!