In Chapter 6 of K&R, we go over accessing elements of a structure by pointers. We are given a function:
struct key *binsearch(char *word, struct key *tab, int n)
{
int cond;
struct key *low = &tab[0];
struct key *high = &tab[n];
struct key *mid;
while (low < high) {
mid = low + (high-low) / 2;
if ((cond = strcmp(word, mid->word)) < 0)
high = mid;
else if (cond > 0)
low = mid + 1;
else
return mid;
}
return NULL;
}
In an earlier version of this program where we weren't using pointers, we could compute mid
as mid = (low+high)/2
but now we need to compute mid
as mid = low + (high-low) / 2
I understand that you can't add pointers because logically the result doesn't return anything useful, but what I don't understand is aren't we still adding pointers with mid = low + (high-low) / 2
? We are adding low
to the result of (high-low)/2
?