The output of this code in C

#include<stdio.h>
int main()
{
    int i, j;
    int *pi,*pj;
    pi=&i;
    pj=&j;

    printf("pi-pj=%d\n",pi-pj);
    return 0;
}

I tried this code for different compilers, but every time I get the same result, can someone help me understand why this is the same?

Conclusion:

pi -pj = 3

I am confused, as the memory would usually be contiguously allocated. So, let's say our system stack grows down, and we have &i = 0xA, then an address j(&j) = 0x6(since integers are 4 bytes). Now, when we print the difference between these two pointer values int, there should be a conclusion "1". But he comes like "3". Why is this?

+5
source share
1 answer

I could not reproduce your experience. C gccon Linux x86:

[wally@lenovotower ~]$ cat t.c
#include<stdio.h>
int main()
{
    int i, j;
    int *pi,*pj;
    pi=&i;
    pj=&j;

    printf("pi-pj=%d\n",pi-pj);
    return 0;
}

[wally@lenovotower ~]$ gcc -o t t.c
[wally@lenovotower ~]$ ./t
pi-pj=1
[wally@lenovotower ~]$ 

, i j . , . , . , .

+5

All Articles