可能重複:
Why do I get a segmentation fault when writing to a string?
Why do I get a segmentation fault when I try to modify a string constant?分段故障而使用char *的字符串,但不能用字符串[11]
我試圖運行下面的兩個代碼和我我得到一個段錯誤file2.c但 file1.c我沒有得到任何過錯。有人可以解釋什麼是下面的代碼之間的區別:
file1.c中
#include <stdio.h>
int main()
{
int i;
char string[11] = {"HelloThere"};
string[10] = '\0';
for(i =0;i<5;i++)
{
string[i] = 'a';
}
printf("%s\n",string);
}
和:
file2.c中
#include <stdio.h>
int main()
{
int i;
char * string;
string = "HelloThere";
for(i =0;i<5;i++)
{
string[i] = 'a';
}
printf("%s",string);
}
這個問題重複了數百次。 –
@Oli - 我認爲這個更好:[爲什麼在寫入字符串時出現分段錯誤?](http://stackoverflow.com/questions/164194/why-do-i-get-a-segmentation當寫入字符串時發生錯誤)或許最好的問題是「爲什麼OP沒有打擾到先搜索?」 –