Search code examples
c++windowsqt32-bit

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


Solution

  • 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