[問題] --i 和i--的不同

看板C_and_CPP作者 (我喜歡溫柔的人)時間11年前 (2014/03/12 00:50), 編輯推噓5(509)
留言14則, 7人參與, 最新討論串1/1
目前在看Cracking the Coding Interview 有一些問題想請教大家 這是用c語言寫的 其中有一題是這樣的 Q:Implement a function void reverse(char* str) in C which reverse a null-terminated string. Answer: void reverse(char *str){ char* end=str; char tmp; if (str){ while(*end){ /*find end of the string */ ++end; } --end; /* set on char back, since last char is null*/ /*swap characters from start of string with the end of the *string, until the pointers meet in the middle. */ while (str <end) { tmp = *str; *str++ = *end; *end-- = tmp; } } } 我有兩個問題: 1. --end 和 end-- 是哪裡不同 2. str< end 是在比較位址的大小嗎 還是pointer 在位址的先後順序 問很基礎的問題,真是不好意思 :p -- 恬靜,閑適安靜,很美好的寧靜 -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 135.0.163.188

03/12 01:36, , 1F
Q1: 在這裡沒不同 Q2 你講的兩個敘述有不一樣嗎?
03/12 01:36, 1F

03/12 01:37, , 2F
Q1: end-- = tmp; //end = tmp; 然後 end-- (--end則相反
03/12 01:37, 2F

03/12 03:08, , 3F
樓上不對, postfix ++ -- 是 rvalue 不能接 =
03/12 03:08, 3F

03/12 03:09, , 4F
prefix ++ -- 是 lvalue 才能接 =
03/12 03:09, 4F

03/12 03:09, , 5F
要舉這種差別還是放到等號右邊去比較不會讓人搞混
03/12 03:09, 5F

03/12 03:09, , 6F
至於 *ptr++ 有一個 deref 在前面事情就不一樣了...
03/12 03:09, 6F

03/12 07:28, , 7F
Q2. 這兩個敘述的確沒有不一樣 你要知道電腦只認得數
03/12 07:28, 7F

03/12 07:29, , 8F
字;可以去翻翻計算機組織或者自己轉型看看
03/12 07:29, 8F

03/12 09:44, , 9F
沒事為何要看crack crack code interview?
03/12 09:44, 9F

03/12 13:19, , 10F
樓上 準備面試阿= =
03/12 13:19, 10F

03/13 00:37, , 11F
i--和--i 單獨使用的話本身是沒差別的
03/13 00:37, 11F

03/13 00:39, , 12F
不過跟其他東西一起用的話 就有差別了
03/13 00:39, 12F

03/13 00:40, , 13F
跟其他東西一起用的話 i-- 是先做這行其他的命令
03/13 00:40, 13F

03/13 00:42, , 14F
在做i-1的動作 --i則是先減在做這行其他的命令
03/13 00:42, 14F
文章代碼(AID): #1J7pxg0v (C_and_CPP)