-2
我正在嘗試反轉字符串。我帶兩個指針,一個指向字符串的開始,另一個指向字符串的末尾。然後我交換指針的值。當換行字符串時切換指針值時出現分段錯誤
int main()
{
char *string = "stack overflow";
int len = strlen(string);
char *end;
char tmp; //temporary variable to swap values
//pointer pointing at the end of the string
end = string+len-1;
printf(" value of start and end %c %c", *string , *end); //correct values printed
while(string<end)
{
tmp = *string;
*string = *end; //segmentation fault
*end = tmp;
*string++;
*end--;
}
return 0;
}
不能修改字符串常量,使用'字符字符串[] =「堆棧溢出」'而不是 – 2013-03-12 23:56:17
您還沒有交換指針值。你正在交換*這些指針指向的值*。無論如何,這已被問了數百次[爲什麼這個C代碼導致了一個分段錯誤?](http://stackoverflow.com/questions/1614723/why-is-this-c-code-causing-a-segmentation -故障) – AnT 2013-03-12 23:57:12