char * const pstr = "abcd";
pstr是指向char的const指针。
我认为我无法修改pstr,但可以修改* pstr,
所以我写下一个代码
#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;
}
但是结果却不如我预期。
我在第14行得到了
segmentation fault (core dumped)
...所以我写下一个代码
#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;
}
但是我不知道为什么?
最佳答案
char * const pstr = "abcd";
pstr
是指向char
的常量指针,您不能正确修改pstr
,但"abcd"
是字符串iteral。而且您不能修改字符串文字。您尝试对其进行修改,因此会遇到分段错误。
关于c - 修改char * const pstr =“abcd”时出现segmentfault;,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32933739/