cannot convert from 'const char [3]' to 'char *' x100000 (Qt Creator C++ Windows 32)

断了今生、忘了曾经 提交于 2019-12-05 13:25:10
Jake Psimos

When you use code like this

char *astring2 = "some letters";

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.

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

String literals are of type char const[N] since C++ was first standardized. At this point C didn't support const and a lot of code assigned string literals to char*. As a result a special rule was present in C++ which allowed initialization of char* from string literals. This rule was immediately deprecated.

C99 introduced a const keyword, too. When C++11 was standardized the deprecated rules was pulled and it is no illegal to initialize a char* from a string literal as it should have been right from the stand. The expectation was that C++ compilers warned about the deprecated assignment since years (and all vendors stated they did), i.e., users had years of lead-time to fix their code.

The obvious fix is to initialize a char const* instead of a char* from a string literal.

If you really need a pointer to a mutable array of chars you can create it and get it initialized using

char array[] = "string literal";
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!