Deprecated string literal conversion to 'char *'

I have a program that declares an array of strings like this:

char *colors[4] = {"red", "orange", "yellow", "blue"}; 

But I get the above compiler warning. It compiles, but I prefer to use the deprecated method (if any). I tried to figure out what this means, but I can't figure it out. I have heard the use of 'const' to 'char', but it would be helpful if anyone could explain what the error means. Thank.

+47
c ++ string char deprecated literals
Mar 10 2018-12-12T00:
source share
3 answers

The lines you enter are red, organge, etc. are "literal" because they are defined inside the program code itself (they are not read directly from disk, user input / stdin, etc.).

This means that if you try to write your colors at any time, you will get direct access to the original input and, thus, edit it. This can lead to some unwanted runtime errors.

When declaring it as const, make sure you never try to write this pointer, and this runtime error can be avoided.

 const char *colors[4] = {"red", "orange", "yellow", "blue"}; 

If you ever wanted to edit these values ​​at run time, you first need to copy the lines.

+70
Mar 10 2018-12-12T00:
source share
 "red", "orange", "yellow", "blue" 

this is a constant string. Creating a non-constant pointer to a constant string is incorrect, so a warning. At the moment you are getting a warning, but it should be a mistake, because it is deprecated in C ++ 03 and is prohibited in C ++ 11.

+8
Mar 10 '12 at 20:50
source share

These answers are correct.

Note that if you have a function that requires an array of characters as an argument, and you pass this argument as follows:

 foo ("bar"); 

The same warning will be shown. In this case, you can:

1) Change it as described in the first answer:

 void foo (char[] str) { printf(str); } const char param[] = "bar"; foo (param); 

2) Consider a standard C ++ string, for example:

 void foo (std::string theParam) { std::cout << theParam; } foo ("bar"); 

IMHO, if there is no real performance problem and you are not working with C libraries, or if you are creating a C ++ library for other users, you are better off working with immutable C ++ strings and their set of functions.

If you want to use Unicode, C ++ support is "terrible" as described here . This question gives you some hints (mainly: using the IBM ICU library). If you already have Qt in your project, QString also do the trick as well as Gettext.

+4
Jul 08 '14 at 12:25
source share



All Articles