Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Output of this C code

Tags:

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 on different compilers, but each time I am getting the same result, can anybody please help me understand why it is the same?

Ouput:

pi -pj = 3

I am confused, as the memory normally would be contiguously allocated. So, if let's say, our system stack is growing downwards and we have &i = 0xA, then the address of j(&j) = 0x6 (since integers are 4 bytes). Now as we are printing the difference between these two int pointer values, output should be "1". But it is coming as "3". Why is that?

like image 254
Learner Avatar asked Jun 29 '11 02:06

Learner


People also ask

What is the output for C code?

Output is dependent on the compiler. For 32 bit compiler it would be fffffffe and for 16 bit it would be fffe.

What does %d do?

%d takes integer value as signed decimal integer i.e. it takes negative values along with positive values but values should be in decimal otherwise it will print garbage value. ( Note: if input is in octal format like:012 then %d will ignore 0 and take input as 12) Consider a following example.


1 Answers

I was not able to replicate your experience. With gcc on 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 ~]$ 

This means that i and j are adjacent. Pointer subtraction returns the number of items between the pointers, not the address difference. To get your result, there would have to be two items-worth of padding in between. I can't explain how that could be.

like image 56
wallyk Avatar answered Oct 11 '22 09:10

wallyk