关于指针的这些陈述是否具有相同的效果?

Pie*_*ter 20 c pointers

做这个...

char* myString = "hello";
Run Code Online (Sandbox Code Playgroud)

......有同样的效果吗?

char actualString[] = "hello";
char* myString = actualString;
Run Code Online (Sandbox Code Playgroud)

Blu*_*eft 33

没有.

char  str1[] = "Hello world!"; //char-array on the stack; string can be changed
char* str2   = "Hello world!"; //char-array in the data-segment; it's READ-ONLY
Run Code Online (Sandbox Code Playgroud)

第一个示例13*sizeof(char)在堆栈上创建一个大小数组,并将字符串复制"Hello world!"到其中.
第二个示例char*在堆栈上创建一个并将其指向可执行文件的数据段中的一个位置,该位置包含该字符串"Hello world!".第二个字符串是READ-ONLY.

str1[1] = 'u'; //Valid
str2[1] = 'u'; //Invalid - MAY crash program!
Run Code Online (Sandbox Code Playgroud)

  • 这就是为什么有些编译器警告你,除非你写'const char*blah ="blahblah"` (2认同)
  • 这也是为什么在C++中,初始化一个`char*`指向一个字符串文字,不赞成要求指针为`char const*`.我明白,与这个C问题并不严格相关; 但它确实展示了该场景的事实. (2认同)