Your particular case is cause for undefined behavior since p
and q
point to unrelated objects.
You can make sense of p-q
only if p
and q
point to the same array/one past the last element of the same array.
int array[10];
int* p = &array[0];
int* q = &array[5];
ptrdiff_t diff1 = q - p; // Valid. diff1 is 5
ptrdiff_t diff2 = p - q; // Valid. diff2 is -5
q - p
is 5 in this case since they point to elements of the array that are 5 elements apart.
Put another way, p+5
is equal to q
. If you start from p
and step over 5 elements of the array, you will point to the same element of the array that q
points to.
As an aside, don't use the format specifier %d
for printing pointers. Use %p
. Use %td
for ptrdiff_t
.
printf(" p is %p\n q is %p\n p-q is :%td", p, q, p-q);`
// ^^ ^^
See http://en.cppreference.com/w/c/io/fprintf for the valid format specifiers for the different types.