Address difference between two integer variables in c

前端 未结 5 1217
醉梦人生
醉梦人生 2021-01-07 07:17
#include 
int main()
{
    int i=10,j=20,diff;
    diff=&j-&i;
    printf(\"\\nAddress of i=%u Address of j=%u\",&i,&j);
    printf(\"         


        
5条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-07 07:44

    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.

提交回复
热议问题