Address difference between two integer variables in c

前端 未结 5 1187
醉梦人生
醉梦人生 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:26

    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.

    0 讨论(0)
  • 2021-01-07 07:33

    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.

    0 讨论(0)
  • 2021-01-07 07:37

    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.

    0 讨论(0)
  • 2021-01-07 07:39

    Did you try:

        diff=(int)&j-(int)&i;
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题