Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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)

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?"

like image 318
Lupe Avatar asked Dec 12 '15 19:12

Lupe


2 Answers

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
like image 59
Jake Psimos Avatar answered Sep 25 '22 14:09

Jake Psimos


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";
like image 29
Dietmar Kühl Avatar answered Sep 21 '22 14:09

Dietmar Kühl