The duplicate question mentions that:
pointer subtraction yields the number of array elements between two pointers of the same type
Read more about it in Pointer subtraction confusion.
However, your code is wrong and ill-formed, since it invokes Undefined Behavior. Please compile with warnings enabled, and you will get:
main.c: In function ‘main’:
main.c:12:7: warning: assignment makes pointer from integer without a cast [-Wint-conversion]
p = arr[1];
^
main.c:13:7: warning: assignment makes pointer from integer without a cast [-Wint-conversion]
q = arr[3];
^
main.c:15:12: warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘long int’ [-Wformat=]
printf("P-Q: %d, P: %d, Q: %d", (p - q), p, q);
^
main.c:15:12: warning: format ‘%d’ expects argument of type ‘int’, but argument 3 has type ‘int *’ [-Wformat=]
main.c:15:12: warning: format ‘%d’ expects argument of type ‘int’, but argument 4 has type ‘int *’ [-Wformat=]
The errors will occur nevertheless. For the warnings, I just used the -Wall
flag.
In order for your code to make sense, you could just declare p
and q
as simple int
s and and not as pointers.
Or, you could do this:
p = &arr[1];
q = &arr[3];
printf("P-Q: %td, P: %p, Q: %p", (p - q), (void *)p, (void *)q);
and get something like this:
P-Q: -2, P: 0x7ffdd37594d4, Q: 0x7ffdd37594dc
Note that I used %td
for printing the result of the subtraction of pointers.