Re: pointer subtraction

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



Hi Ivan,

>What can be assummed about the value of one pointer - a second pointer?

Given...
T* array = new T[100];
T* p1 = &array[0];
T* p2 = &array[99];
ptrdiff_t diff1 = p1 - p2;
ptrdiff_t diff2 = p2 - p1;

Doing...
T* p3 = p2 + diff1;
T* p4 = p1 + diff2;

You can assume p3 == p1, and p2 == p4.

Unless I messed up. :-)

>If you substract the lower address pointer from the higher would you expect to
get a positive value?

No.  I expect to get a magic value that represents the difference between
the two pointers.

Keep in mind that array[i] is short hand for *(array + i), which under the
covers could be considered something like *(T*)((char*)array + i *
sizeof(T)).

>If you subtract the same two pointers would you expect to see the same result
each time?

Yes.  Where "same" means "exactly the same in all respects".

But not in this situation:

T array[5];
char* c1 = (char*)&array[0];
char* c2 = (char*)&array[4];
long* l1 = (long*)&array[0];
long* l2 = (long*)&array[4];

ptrdiff_t diff1 = c2 - c1;
ptrdiff_t diff2 = l2 - l1;

Here I do not expect diff2 == diff1.  I'd be shocked if they were equal.

>Also what does the result actually represent?

The difference between two pointers.

HTH,
--Eljay



[Index of Archives]     [Linux C Programming]     [Linux Kernel]     [eCos]     [Fedora Development]     [Fedora Announce]     [Autoconf]     [The DWARVES Debugging Tools]     [Yosemite Campsites]     [Yosemite News]     [Linux GCC]

  Powered by Linux