从字符串字面值到“char *”的弃用转换 [英] Deprecated conversion from string literal to 'char*'

查看:915
本文介绍了从字符串字面值到“char *”的弃用转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个程序,声明这样的字符串数组:

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

但我得到了上面的编译器警告。它编译,但我宁愿使用非deprecated的方式(如果有一个)。我试图找出它的意思,但我似乎不能弄清楚。我听说过'char'工作之前使用'const',但是如果有人能解释错误的含义会很有帮助。感谢。

解决方案

输入的字符串:red,organge等是literal里面的程序代码本身(他们不是直接从磁盘读取,用户输入/ stdin等)。



这意味着如果在任何时候,你试图写你的 colors ,您将直接访问您的原始输入,从而编辑它。这将导致一些不希望的运行时错误。



声明为一个const将确保你永远不会尝试写入这个指针和这样的运行时错误可以避免。

  const char * colors [4] = {red,orange,yellow蓝色}; 

如果你想在运行时编辑这些值,那么你应该先复制字符串。 p>

I have a program which 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'd rather use the non-deprecated way(if there is one). I've tried to find out what it means, but I can't seem to figure it out. I've heard using 'const' before 'char' works, but it would be helpful if someone could explain what the error means. Thanks.

解决方案

The strings that you enter: "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 at any point you try to write to your colors you will be directly accessing your original input and thus editing it. This would cause some undesired run-time errors.

Declaring it as a const will make sure that you will never try to write to this pointer and such a run-time error can be avoided.

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

If you ever feel like editing these values at runtime, then you should copy the strings first.

这篇关于从字符串字面值到“char *”的弃用转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆