不推荐将字符串文字转换为 'char*'

编程入门 行业动态 更新时间:2024-10-24 06:27:26
本文介绍了不推荐将字符串文字转换为 '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*'

本文发布于:2023-07-28 14:10:03,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1231641.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:转换为   字符串   文字   char

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!