无法从“const char [3]"转换为“char *"x100000(Qt Creator C++ Windows 32) [英] cannot convert from 'const char [3]' to 'char *' x100000 (Qt Creator C++ Windows 32)
问题描述
就在五分钟前,当我点击 f5 并出现 102 个错误时,一切正常:
Everything was working fine just five minutes ago when I tapped f5 and got 102 errors:
error: C2440: 'initializing' : cannot convert from 'const char [17]' to 'char *'
Conversion from string literal loses const qualifier (see /Zc:strictStrings)
那个特定的在第 30 行:
That specific one is at line 30:
char* hexchars = "0123456789ABCDEF";
我至少一个星期没有碰过错误所在的文件.我通常会说我不小心更改了编译参数或其他东西,但在它开始出错之前我没有打开设置.
I haven't touched the file the errors are in for at least a week. I'd normally say I accidentally changed something in the compile args or something, but I haven't opened settings since much before it started erroring.
有什么想法吗?我一定是心不在焉地改变了一些设置,但我真的不记得想过呃,我刚刚做了什么?"
Any ideas? I must have absentmindedly changed some setting but I really can't remember thinking "uh oh what did I just do?"
推荐答案
当你使用这样的代码时
char *astring2 = "some letters";
C++(和 C)将其放入只读内存中.您不能修改用文字初始化的 char 指针的内容,即使它不是 const.
C++ (and C) puts that into read only memory. You can not modify the contents of a char pointer initialized with a literal even if it is not const.
同样你也不能改变指针的地址,因为上面的规则会导致内存泄漏.
Also you can not change the address of the pointer because it will cause a memory leak due to the rule above.
但是,除非您将其设置为 const,否则这不符合该规则:
This, however, does not follow that rule UNLESS you make it const:
char astring[] = "some letters that can be changed";
char *ptrToString = astring; //work
astring2 = astring //not work
这篇关于无法从“const char [3]"转换为“char *"x100000(Qt Creator C++ Windows 32)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!