#include<stdio.h>
int main()
{
int i=10,j=20,diff;
diff=&j-&i;
printf("\nAddress of i=%u Address of j=%u",&i,&j);
printf("\nDifference of address i and j is %d\n",diff);
return 0;
}
The output I got is:
Address of i=3012788 Address of j=3012776
Difference of address i and j is -3
But the difference between the addresses here is 2.
When I do diff=&i-&j, I get the following output:
Address of i=2751740 Address of j=2751728
Difference of address i and j is 3
But the difference here between the addresses is 12.
When two 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. But why the differences are not actually what it has to be?
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 *pointerpointer1 - pointer2 actually means (pointer1 - pointer2) / sizeof *eitherSo you expect 12 and you get 3 = 12 / 4. That's because an int on your platform is 4 bytes long.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With