[問題] binary search 指標參數問題
Win10
gcc
goo.gl/Q3ybkG
p145,146
大意就是拿一個字串跟結構陣列裡面的每個字串成員做比較,找到一樣的字串
結構陣列的字串已經是由小到大的排列了
int binsearch(char *word, struct key tab[], int n)
n是陣列大小,在binsearch裡面
low = 0;
high = n - 1;
後來又改成一個指標指到結構版本 p148,149
struct key *low = &tab[0];
struct key *high = &tab[n];
請問為什麼這邊的n就不減一了?
後面寫到
The initializers for low and high are now pointers to the beginning and just
past the end of the table(陣列結尾的下一位)
mid = (low+high)/2 /* WRONG */
because the addition of pointers is illegal. Subtraction is legal, however,
so high-low is the number of elements, and thus
mid = low + (high-low)/2
應該只是說指標不能相加,但是可以相減,雖然第二種也可以避免overflow的問題
但還是不懂為什麼n不減一
謝謝
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 211.75.14.196
※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1498790695.A.02C.html
※ 編輯: anoymouse (211.75.14.196), 06/30/2017 10:47:47
→
06/30 11:40, , 1F
06/30 11:40, 1F
→
06/30 11:40, , 2F
06/30 11:40, 2F
→
06/30 12:33, , 3F
06/30 12:33, 3F
→
06/30 12:34, , 4F
06/30 12:34, 4F
→
06/30 12:38, , 5F
06/30 12:38, 5F
→
06/30 12:38, , 6F
06/30 12:38, 6F
→
06/30 13:05, , 7F
06/30 13:05, 7F
→
06/30 13:10, , 8F
06/30 13:10, 8F
→
06/30 14:05, , 9F
06/30 14:05, 9F
→
06/30 15:59, , 10F
06/30 15:59, 10F
→
06/30 15:59, , 11F
06/30 15:59, 11F