我想弄清楚使用指針基於索引值從字符串中刪除字符的方法,而不是觸摸數組表示法(我從本質上不使用任何數組括號內)。據我瞭解,* letter = temp應該將temp中的內容分配給字母的位置,但它會產生分段錯誤。嘗試使用指針從字符串中刪除字符
char *word = "blue";
int length = strlen(word);
int index = 0;
for (index; index < length; index++)
{
char *letter = word + index;
char temp;
temp = *(letter + 1);
*letter = temp;
}
printf("%s\n", word);
編輯:粗暴的東西,答案似乎忽略。
去它不會讓你改變了字符串文字。嘗試改爲'char word [] =「blue」;' – BLUEPIXY 2014-09-27 01:09:29
* Dozens *與這個問題有關的重複,其中一個寫得很好:[爲什麼在寫入字符串時出現段錯誤?](http:// stackoverflow .com/questions/164194/why-do-i-get-a-segmentation-fault-when-writing-to-a-string) – WhozCraig 2014-09-27 01:23:35
我的解決方案避免了括號。 Bluepixy在任何其他問題上都是正確的。 – 2014-09-27 01:32:58