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