Programming

(C++) deprecated conversion from string constant to 'char*'

steloflute 2013. 3. 1. 12:51

http://en.wikibooks.org/wiki/GCC_Debugging/g%2B%2B/Warnings/deprecated_conversion_from_string_constant


Causes

Initializing a character pointer variable with a string literal

In standard C, string literals have type char *, even though they cannot be modified without invoking undefined behavior (risking a program crash or data corruption). g++ issues a warning to let you know that you are relying on this behavior.

char *x = "foo bar";

Solution 1: Change the "char *" to "const char *"

Most programmers assign all string literals to a pointer of type const char *, which ensures that they cannot be accidentally written to.

const char *x = "foo bar";

Solution 2: Use a string object instead of a character pointer

string x = "foo bar";

Solution 3: Cast the string literal to type "char *"

char *x = (char *)"foo bar";