2014-09-27 40 views
-1

我想弄清楚使用指針基於索引值從字符串中刪除字符的方法,而不是觸摸數組表示法(我從本質上不使用任何數組括號內)。據我瞭解,* 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); 

編輯:粗暴的東西,答案似乎忽略。

+0

去它不會讓你改變了字符串文字。嘗試改爲'char word [] =「blue」;' – BLUEPIXY 2014-09-27 01:09:29

+0

* 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

+0

我的解決方案避免了括號。 Bluepixy在任何其他問題上都是正確的。 – 2014-09-27 01:32:58

回答

0

我已經把我的意見在代碼中關於什麼是對

/* normally we would do char word[] = "blue" but that isn't allowed 
    * We need to put it on the heap where it can be modified but 
    * we can't use array indexing [] so we can do the hack 
    * below */ 

    /* String constants are immutable - they can't be changed 
    * so consider them read only. Trying to modify one can 
    * lead to undefined behavior including write fault */ 
    char *constWord = "blue"; 
    int index = 0; 
    int length = strlen(constWord); 

    /* Create space on the heap to hold the string + nul terminator */ 
    char *word = malloc(strlen(constWord + 1)); 

    /* Copy the string to the heap where it can be modified */ 
    strcpy(word, constWord); 

    for (index; index < length; index++) { 
     char *letter = word + index; 
     char temp; 
     temp = *(letter + 1); 
     *letter = temp; 
    } 

    printf("%s\n", word); 

    /* Cleanup */ 
    free(word); 
} 
0

word是一個指針,它被初始化爲指向一個字符串常量。指針word可能會被修改爲指向另一個字符串,但是如果您嘗試修改word指向的字符串,則結果是未定義的。你可以做char word[] = "blue"。這裏的word是一個足夠大的數組,可以容納一個單詞並在該單詞後面輸入\0。數組中的單個字符可以更改,但數組的地址將保持不變。