为什么我会收到将字符串文字转换为char *的编译器警告,这不好吗? [英] Why do I get a compiler warning for converting a string literal to a char*, is it bad?

查看:99
本文介绍了为什么我会收到将字符串文字转换为char *的编译器警告,这不好吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以编译器告诉我这是从字符串文字到char *的不推荐使用的转换:

So the compiler tells me this is a deprecated conversion from a string-literal to char*:

 char* myString = "i like declaring strings like this";

我应该为此担心吗?这是错误的方法吗?

Should I be worried about this? Is this the wrong way to do this?

我需要将 myString 传递给接受<$的函数c $ c> char * ,我应该在没有这种转换的情况下正确初始化 char * 吗?

I need to pass myString to a function that accepts a char* , who should I properly initialize the char* without this conversion?

推荐答案

它甚至不应该编译。如果需要将其传递给函数,以确保不会更改需要使用const cast的字符串,则其正确用法之一是:

It shouldn't even compile. If you need to pass it to function that you are sure won't change the string you need to use const cast, its one of its correct uses:

functionName(const_cast<char *>("something"));

或者,如果您不希望使用const强制转换,则可以将字符串复制到堆栈中: / p>

Or if you don't want the const cast, you can copy the string to the stack:

char str[] = "something";
functionName(str);

这篇关于为什么我会收到将字符串文字转换为char *的编译器警告,这不好吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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