[問題] binary search 指標參數問題

作者: anoymouse (沒有暱稱)   2017-06-30 10:44:53
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不減一
謝謝
作者: Hazukashiine (私は幸せです)   2017-06-30 11:40:00
不管是 n 還是 n-1 結果都一樣 只是找中間值附而已近
作者: aiwhat   2017-06-30 12:33:00
n 沒減一的後面的 while 有調整成 low < high原本的是 low <= high,做的事情是一樣的只差在一個用 [low, high] 表示搜尋範圍,另一個用[low, high)表示
作者: anoymouse (沒有暱稱)   2017-06-30 13:05:00
所以只是想強調取到陣列範圍外下一個元素是合法的?謝謝兩位回答!!
作者: Hazukashiine (私は幸せです)   2017-06-30 14:05:00
指向陣列後面一個元素的指標合法 但存取該指標則否
作者: anoymouse (沒有暱稱)   2017-06-30 15:59:00
是 書上也有寫到 可以reference 不能dereference謝謝!

Links booklink

Contact Us: admin [ a t ] ucptt.com