From C11 Standard#6.5.6p9 [emphasis added]
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. The size of the result is implementation-defined, and its type (a signed integer type) is ptrdiff_t defined in the <stddef.h> header. ....
From this:
The subscript which specifies a single element of an array is simply an integer expression in square brackets.
int a[5] = {1,2,3,4,5};
int *p = a;
int *q = p++;
Both pointer p
and q
pointing to elements of same array object i.e. array a
. Pointer p
is pointing to second element of array a
, which is a[1]
(subscript is 1
) and pointer q
is pointing to first element of array a
, which is a[0]
(subscript is 0
).
The result of p - q
is 1 - 0
which is equal to 1
. Hence, you are getting output 1
.
Ideally, the type of b
should be ptrdiff_t
and provide %td
format specifier to printf()
for b
:
ptrdiff_t b = p - q;
printf("%td", b);