char * const pstr = "abcd";
PSTR是一个const字符指针...... 我想,我不能修改PSTR,但我可以修改* PSTR, 所以我写了下面的代码段错误时修改char * const pstr =“abcd”;
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
// The pointer itself is a constant,
// Point to cannot be modified,
// But point to a string can be modified
char * const pstr = "abcd"; // Pointer to a constant
// I find that pstr(the address of "abcd") is in ReadOnly data
// &pstr(the address of pstr) is in stack segment
printf("%p %p\n", pstr, &pstr);
*(pstr + 2) = 'e'; // segmentation fault (core dumped)
printf("%c\n", *(pstr + 2));
return EXIT_SUCCESS;
}
但结果不像我预料的那样。 我得到了segmentation fault (core dumped)
在线路14 ... 所以我写了下面的代码
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
// The pointer itself is a constant,
// Point to cannot be modified,
// But point to a string can be modified
char * const pstr = "abcd"; // Pointer to a constant
// I find that pstr(the address of "abcd") is in ReadOnly data
// &pstr(the address of pstr) is in Stack segment
printf("%p %p\n", pstr, &pstr);
*(pstr + 2) = 'e'; // segmentation fault (core dumped)
printf("%c\n", *(pstr + 2));
return EXIT_SUCCESS;
}
但我不知道是什么原因???
您正在尝试修改字符串文字。请参见[this](http://stackoverflow.com/questions/10202013/change-string-literal-in-c-through-pointer)。 – SSWilks
可能的重复[为什么在写入使用“char \ * s”初始化但不是“char s \ [\]”的字符串时出现分段错误?](http://stackoverflow.com/questions/164194/为什么-DO-I-GET-A-分割的故障时,写入到一个字符串初始化-与-CHA) – SSWilks