Pointer subtraction confusion

The idea is that you're pointing to blocks of memory

+----+----+----+----+----+----+
| 06 | 07 | 08 | 09 | 10 | 11 | mem
+----+----+----+----+----+----+
| 18 | 24 | 17 | 53 | -7 | 14 | data
+----+----+----+----+----+----+

If you have int* p = &(array[5]) then *p will be 14. Going p=p-3 would make *p be 17.

So if you have int* p = &(array[5]) and int *q = &(array[3]), then p-q should be 2, because the pointers are point to memory that are 2 blocks apart.

When dealing with raw memory (arrays, lists, maps, etc) draw lots of boxes! It really helps!


So that the answer is the same even on platforms where integers are different lengths.


Because everything in pointer-land is about offsets. When you say:

int array[10];
array[7] = 42;

What you're actually saying in the second line is:

*( &array[0] + 7 ) = 42;

Literally translated as:

* = "what's at"
(
  & = "the address of"
  array[0] = "the first slot in array"
  plus 7
)
set that thing to 42

And if we can add 7 to make the offset point to the right place, we need to be able to have the opposite in place, otherwise we don't have symmetry in our math. If:

&array[0] + 7 == &array[7]

Then, for sanity and symmetry:

&array[7] - &array[0] == 7

Tags:

C