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?
qandpare two different pointer variables. They are not two different elements of the same array (of pointers). Therefore&qand&pare two pointers (to pointers) that do not point to elements of the same array (nor one past its end). Therefore evaluating&q - &pcauses 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
qandphappen to be allocated at adjacent addresses on the stack, withqat a higher address thanp, and that the compiler implements&q - &pby 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 print47orBUGor delete all your files.Note that what
qandpthemselves point to is entirely irrelevant; the arrayahas nothing to do with your code as it stands.You may have been thinking of doing
q-pinstead. That would be subtracting pointers to two different elements of theaarray. 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%xwhich is only valid for an argument of typeunsigned; this causes undefined behavior as well. The correct format specifier would be%td.)