Deprecated conversion from string literal to 'char*'

后端 未结 3 1817
无人及你
无人及你 2020-12-01 02:13

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

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

But I get the

3条回答
  •  攒了一身酷
    2020-12-01 02:13

    These answers are all correct.

    Note that if you have a function requiring an array of characters as an argument and you pass this argument like this:

    foo ("bar");
    

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

    1) Change it like this, as explained in the first answer:

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

    2) Consider using a C++ standard string, like so:

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

    IMHO, as long as no real performance issue is concerned and you are not working with C libraries, or if you are building a C++ library for others to use, you should rather work with C++ immutable strings and their feature set.

    If Unicode is a requirement, the support in C++ is "terrible" as explained here. This question gives you some clues (mainly: use IBM ICU library). If you already have Qt in your project, QString will also do the trick, and so will Gettext.

提交回复
热议问题