main(){
char a[20],*p,*q;
p=&a[0];
q=&a[10];
printf ("%d\n",&q - &p) }
This C program gives o/p as:
1
As I understand, the values stored at those addresses are garbage. How can their subtraction be 1?
Can anyone please explain how?
q
andp
are two different pointer variables. They are not two different elements of the same array (of pointers). Therefore&q
and&p
are two pointers (to pointers) that do not point to elements of the same array (nor one past its end). Therefore evaluating&q - &p
causes undefined behavior, and it is not possible to use the language definition to reason about what may or may not happen beyond that point.See also Is subtraction of pointers not pointing to different elements of same array valid in C?.
What might be happening in your program is that
q
andp
happen to be allocated at adjacent addresses on the stack, withq
at a higher address thanp
, and that the compiler implements&q - &p
by subtracting their actual addresses and dividing by their size. That would account for a value of 1. But the compiler is in no way obliged to do this; it could, in principle, instead print47
orBUG
or delete all your files.Note that what
q
andp
themselves point to is entirely irrelevant; the arraya
has nothing to do with your code as it stands.You may have been thinking of doing
q-p
instead. That would be subtracting pointers to two different elements of thea
array. It is perfectly well defined, and the result would be 10.(By the way, the result of subtracting two pointers has type
ptrdiff_t
. You are using the printf specifier%x
which is only valid for an argument of typeunsigned
; this causes undefined behavior as well. The correct format specifier would be%td
.)