Adding Pointer Addresses - Legality

Since adding two pointers together is illegal, how is this piece of code valid?

struct key *low = &tab[0]; 
struct key *high = &tab[n]; 
struct key *mid; 

while (low < high) 
{ 
  mid = low + (high-low) / 2; //isn't this adding pointers?


//code continues...

The first statement in the while loop seems to add two addresses together, how is this legal?

This code is from K & Rs C programming language on page 122

+4
source share
4 answers

The difference between the two pointers ( high - low) is an integer (actually ptrdiff_t, which is a signed integer type), so you add an integer to the pointer, which is completely legal. This also explains why it is perfectly normal to split the difference by 2, which is not what you could do with a pointer.

+6

( ptrdiff_t), . C99 6.5.6 paragrph 2:

, , . ( 1.)

3:

:

:

;

, , 9, :

, , ; [...]

undefined , , , , 8, :

[...] , ; undefined. , * , .

+4

high - low - ( ptrdiff_t, ). .

+2

, , , ( ) . , ptrdiff_t, stddef.h.

So, high - lowreturns this signed integer, which is then added to a minimum. This way you are not adding pointers, you are adding a pointer with an integer sign.

+1
source

All Articles