不推荐将字符串文字转换为 'char*' [英] Deprecated conversion from string literal to 'char*'

查看:35
本文介绍了不推荐将字符串文字转换为 'char*'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个程序,它声明一个字符串数组,如下所示:

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

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

但我收到了上述编译器警告.它可以编译,但我宁愿使用不推荐的方式(如果有的话).我试图找出它的含义,但我似乎无法弄清楚.我听说在 'char' 起作用之前使用 'const',但如果有人能解释错误的含义会很有帮助.谢谢.

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.

推荐答案

您输入的字符串:red"、organge"等是literal",因为它们是在程序代码本身内部定义的(它们不会被读取)直接从磁盘、用户输入/stdin 等).

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.).

这意味着,如果您在任何时候尝试写入 colors,您将直接访问您的原始输入并因此对其进行编辑.这会导致一些不需要的运行时错误.

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.

将其声明为 const 将确保您永远不会尝试写入此指针,并且可以避免此类运行时错误.

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天全站免登陆