a
contains the adress of the variable j
(which contains itself the adress of variable i
)
b
is the adress of l
.
Then the first two printf
show you the adresses where variables j
and l
have been allocated to.
In your example j
and l
are contiguous in memory (I assume int
is 32 bits on your architecture). It is just by luck, they could have been located far away from each other.
Finally, when you substract 2 pointers as in the last printf
, you are doing arithmetic on pointers.
Incrementing a pointer adds to the adress the length of the type pointed to. For example if you print the values of variables j
and l
(not their adresses) you would find a difference of 4 between both adresses.
Similarly, the substraction of both adresses equals 4
which represent a difference of 1
in terms of pointer arithmetic for 32 bits architecture. That's why it prints the value 1
.
However keep in mind that pointer arithmetic can be tricky. About substraction the C99 Standard states that:
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
So here I think you are allowed to substract a
and b
but this is not something you want to do in a real code.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…