From standard 6.5.6
When two pointers are subtracted, both shall point to elements of the
same array object, or one past the last element of the array object;
the result is the difference of the subscripts of the two array
elements.
Here if you consider it an one element array, then two pointers - one of them are pointing to that element and 1 past the element. So that results in 1. The above rule obviously tells us that the result is scaled up by the sizeof the type that the pointers points to.
Also from same standard 6.5.6 where it is specified that 1 past the array element a pointer can point
Moreover, if the expression P
points either to an element of an
array object or one past the last element of an array object, and the
expression Q
points to the last element of the same array object,
the expression ((Q)+1)-(P)
has the same value as ((Q)-(P))+1and as
-((P)-((Q)+1)), and has the value zero if the expression P points one past > the last element of the array object, even though the
expression (Q)+1 does not point to an element of the array object
If I cast them into void *, I will get 32 right ?
Yes. it will be 32
(if you are using gcc
). sizeof(void)=1
(gcc makes it like that - not specified standard) but most probably other compiler will generate error which can be resolved by using char*
.As sizeof char
is 1
you can use char*
casting to get the same result. As per standard this is not specified and illegal since void
is an incomplete type.
Better to use char*
casting to get the difference in bytes.