#include
int main()
{
int i=10,j=20,diff;
diff=&j-&i;
printf(\"\\nAddress of i=%u Address of j=%u\",&i,&j);
printf(\"
Computing the difference between pointers that do not point into the same array (as in your case) is undefined behavior in C. See this for more information and references.
You are using pointer arithmetic. Because int is 4 bytes on your machine, result * 4 is the distance between the two address. However you can apply conversion like (int) on the pointers to get what you expected.
When an 2 integer variables are declared its not necessary for the second variable to occupy the next four bytes of the address occupied by the first variable?
NO, The address can be anywhere, the compiler chosses, unless ofcourse you have an array.
Did you try:
diff=(int)&j-(int)&i;
First of all, it's not legal to do arithmetic on addresses that are not from the same block of memory (array etc).
You second question is more interesting. You are subtracting two addresses and it defies arithmetic. Here is what is happening.
This is how pointer arithmetic works:
pointer + x
actually means pointer + sizeof *pointer
pointer1 - pointer2
actually means (pointer1 - pointer2) / sizeof *either
So you expect 12
and you get 3 = 12 / 4
. That's because an int
on your platform is 4 bytes long.