Why do I get a compiler warning for converting a string literal to a char*, is it bad?

后端 未结 2 1835
别那么骄傲
别那么骄傲 2021-01-21 08:04

So the compiler tells me this is a deprecated conversion from a string-literal to char*:

 char* myString = \"i like declaring strings like this\";
2条回答
  •  灰色年华
    2021-01-21 08:37

    Yes, You should be worried about it!

    You should be declaring it as:

    const char* myString = "i like declaring strings like this";
    

    mystring is an pointer to the string literal "i like declaring strings like this", and the string literal resides in an memory space(Implementation Defined) which should not be modified by your program.
    Modifying a string literal results in Undefined behavior.

    Hence, C++03 Standard deprecated declaring string literals without the keyword const, This ensures that the string literal cannot be modified through the pointer.


    Answer to your Question Edit, is already posted by @Benjamin in comments, simply quoting his answer:

    Use an array:
    char myString[] = "i like declaring strings like this";
    That copies the literal into the array, and the copy can be modified

提交回复
热议问题