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

試著忘記壹切 提交于 2019-12-02 01:32:10

问题


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

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

Should I be worried about this? Is this the wrong way to do this?

I need to pass myString to a function that accepts a char* , who should I properly initialize the char* without this conversion?


回答1:


It shouldn't even compile. If you need to pass it to function that you are sure won't change the string you need to use const cast, its one of its correct uses:

functionName(const_cast<char *>("something"));

Or if you don't want the const cast, you can copy the string to the stack:

char str[] = "something";
functionName(str);



回答2:


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



来源:https://stackoverflow.com/questions/7867842/why-do-i-get-a-compiler-warning-for-converting-a-string-literal-to-a-char-is-i

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