C++ 将字符串文字分配给 char*

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8356223/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 18:25:28  来源:igfitidea点击:

Assign a string literal to a char*

c++stringpointerscharliterals

提问by Pietro M

Possible Duplicate:
How to get rid of deprecated conversion from string constant to ‘char*'warnings in GCC?

可能的重复:
如何消除deprecated conversion from string constant to ‘char*'GCC 中的警告?

This assignment:

这个任务:

char *pc1 = "test string";

gives me this warning:

给我这个警告:

warning: deprecated conversion from string constant to 'char*'

警告:不推荐使用从字符串常量到 'char*' 的转换

while this one seems to be fine:

虽然这个似乎没问题:

char *pc2 = (char*)("test string");

Is this one a really better way to proceed?

这是一种更好的方法吗?

Notes: for other reasons I cannot use a const char*.

注意:由于其他原因,我不能使用const char*.

回答by Wyzard

A string literal is a const char[]in C++, and may be stored in read-only memory so your program will crash if you try to modify it. Pointing a non-const pointer at it is a bad idea.

字符串文字是const char[]C++ 中的 a,并且可能存储在只读内存中,因此如果您尝试修改它,您的程序将会崩溃。将非常量指针指向它是一个坏主意。

回答by NPE

In your second example, you must make sure that you don't attempt to modify the the string pointed to by pc2.

在第二个示例中,您必须确保不尝试修改 指向的字符串pc2

If you do need to modify the string, there are several alternatives:

如果确实需要修改字符串,有几种选择:

  1. Make a dynamically-allocated copy of the literal (don't forget to free()it when done):

    char *pc3 = strdup("test string"); /* or malloc() + strcpy() */

  2. Use an array instead of a pointer:

    char pc4[] = "test string";

  1. 制作文字的动态分配副本(完成后不要忘记free()它):

    char *pc3 = strdup("test string"); /* or malloc() + strcpy() */

  2. 使用数组而不是指针:

    char pc4[] = "test string";

回答by Mahesh

That depends on whether you need to modify the string literal or not. If yes,

这取决于您是否需要修改字符串文字。如果是,

char pc1[] = "test string";