我们正在处理一个常量指针, 所以它持有的地址不能改变。 但是该引用的内存地址的内容应该是可变的...
我仍然在尝试这样做时遇到编译/段错误。
#include <stdio.h>
#include <stdlib.h>
int main(void) {
char * const c_ptr = "firstValue"; // now c_ptr is a const ptr to an immutable string literal,
//we can't change it unless we declare char [] instead
printf("%s",c_ptr);
*c_ptr="hsdsdsd"; // better to use strcpy(c_ptr, "hsdsdsd");
printf("%s",c_ptr);
return 0;
}
main.c: In function 'main':
main.c:8:8: warning: assignment makes integer from pointer without a cast [enabled by default]
*c_ptr="hsdsdsd";Segmentation fault (core dumped)
最佳答案
好吧,对于常量指针,指针指向的数据可以更改,但当您使用字符串文字对其进行初始化时则不会。它们具有 char *
类型但无法更改的相当奇怪的特性。
所以,你可以这样做:
char data[10] = "foobar";
char * const ptr = data;
printf("%s\n", ptr); // prints foobar
*ptr = 'z';
printf("%s\n", ptr); // prints zoobar
关于c - 设置后如何更改 char * const 的内容 (C),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43226374/