作者timrau (沒code沒真相)
看板EE_DSnP
標題Re: [問題] addHistory function
時間Sun Mar 30 23:14:23 2008
※ 引述《fairyflame (妖精火燄)》之銘言:
: 這個應該跟作業無關 我只是純粹想知道code寫的意義而已@__@"
: 在addhistory這個function裡
: // remove ' ' at the end
: char* tmp = _readBufEnd - 1;
: while ((tmp >= _readBuf) && (*tmp == ' ')) *(tmp--) = 0;
: // remove ' ' in the beginning
: tmp = _readBuf;
: while (*tmp == ' ') ++tmp;
: // add to _history
: if (*tmp != 0) {
: addHistoryStr(tmp);
: _history[++_historySize].clear();
: _historyIdx = _historySize;
: }
: 在remove ' 'at the end裡
: *(tmp--) = 0;的意義到底是什麼呢@@?
: 是作為一個flag當add history時不要把它給加進去
: 那為什麼remove ' 'in the beginning 就不用令*(tmp)=0呢?
因為這裡的做法是直接改動"字串開頭的地方"
不然*tmp = 0就直接把字串清空了(開頭即是結尾)
: 當判斷式if (*tmp != 0)時 那其它原本輸入若有0的字串不會有問題嗎@@"
: 雖然跟作業不太有太大的關係 但還是想知道為什麼想這樣寫
: 懇請開示 謝謝<(_ _)>
Assume at the beginning
"abcdefg
0" where
0 means '\0'
^ ^-- _readBufEnd
_readBuf
after char* tmp = _readBufEnd - 1;
"abcdefg
0"
^-- tmp
while ((tmp >= _readBuf) && (*tmp == ' ')) is true now, so *(tmp--) = 0;
which means,
replace the char pointed by tmp by 0, and then decrease tmp
by 1
"abcdefg
00"
^-- tmp
Again, the "while ..." is true, and then
"abcdefg
000"
^-- tmp
Now, the "while ..." becomes false.
Since the string should be terminated by '\0',
the string becomes "abcdefg" now.
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 140.112.5.50
※ 編輯: timrau 來自: 140.112.5.50 (03/30 23:18)
1F:推 fairyflame:感謝饒神的開示<(_ _)> 03/31 13:47
2F:推 battlecruise:請問 '\0' 跟 0的意義是一樣的嗎? 04/01 22:35
3F:推 ric2k1:char ch = '\0' 與 ch = 0 是一樣的; 但和 ch = '0' 不同 04/01 23:32