Assign a string literal to a char* [duplicate]

半腔热情 提交于 2019-11-29 13:14:46

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.

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

char pc1[] = "test string";

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";

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!