Assign a string literal to a char* [duplicate]

2020-02-13 08:52发布

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

This assignment:

char *pc1 = "test string";

gives me this warning:

warning: deprecated conversion from string constant to '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*.

3条回答
SAY GOODBYE
2楼-- · 2020-02-13 09:03

In your second example, you must make sure that you don't attempt to modify the the string pointed to by 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";

查看更多
姐就是有狂的资本
3楼-- · 2020-02-13 09:08

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.

查看更多
闹够了就滚
4楼-- · 2020-02-13 09:29

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

char pc1[] = "test string";
查看更多
登录 后发表回答