我剛剛遇到了一些非常奇怪的事情。我的字符串(我們稱之爲word
)在打印時會顯示額外的字母。
受污染的字母取決於:閱讀和打印C字符串中的一個特殊錯誤C
- 正確前綴字的長度。
- 單詞後的空格數。
我從line
解析word
,這只是一行形式的標準輸入。我使用的功能readWord
得到word
出line
的:
void readWord(char **linePointer, char **wordPointer){
char *line = *linePointer;
char *word = *wordPointer;
while (!isEndOfLine(line) && isLowerCaseLetter(*line)){
*word = *line;
word++;
line++;
}
word++;
*word = '\0';
printf("The retrieved word is: %s.\n", *wordPointer)
*linePointer = line;
}
我的輸入/輸出如下所示(請注意,我所說的readWord
功能後照顧insert
之間的空格):
// INPUT 1 :
insert foo
insert ba // several spaces after 'ba'
// OUTPUT 2:
The retrieved word is foo.
The retrieved word is bas.
// INPUT 1 :
insert foo
insert ba // several spaces after 'bar'
// OUTPUT 2:
The retrieved word is foo.
The retrieved word is bare.
我在想我是否正確地分配*word
,我想我做的:
root.word = (char *)malloc(sizeof(char *)); //root is my structure
此外,它不太可能與重新分配
word
字符串的某些錯誤相關,因爲它在
readWord()
函數的開始處已完全清楚。
謝謝你的幫助。這對我來說的確是一個具有挑戰性的錯誤,我不知道我還能做什麼。
UPDATE
事實證明,我確實有一些問題,分配/重新分配,因爲:
//INPUT
insert foo//no spaces
insert bar //spaces here
//OUTPUT
word variable before calling readWord function: ' '.
The retrieved word is foo.
word variable before calling readWord function: 'insert foo
'.
The retrieved word is bare.
你需要爲你操作的字符串分配足夠的內存。你不這樣做。 – milleniumbug
循環之後的'word ++'太多了 – ryanpattison
@rpattiso謝謝!確實如此。但是'word'在第一行之後沒有被清除,所以不止有一個bug。我會研究@milleniumbug說的。 –