pointer arithmetic (char*) &a[1] - (char *)&a[0] == 4

c, casting, pointers

Solution

Pointer math operates on the size of the data structure its pointing to. This is because if I do this:

int array[10] ;
int * p = array ;

p ++ ;

I want `p` pointing at the second int, not some memory halfway in between two elements.

So `&a[1]` is four bytes apart from `&a[0]` but asking it `&a[1] - &a[0]` asks how many `ints` apart it is. When you cast it to `char` you ask for the math in terms of the size of `char`.

Problem

If a is an int array, `(char*) &a[1] - (char *)&a[0]` is equal to 4, while `&a[1] - &a[0]` is equal to 1. why is that?

Original source