1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

please tell me how it is getting its output..

Discussion in 'C' started by Ankur Kamboj, Aug 19, 2011.

  1. Ankur Kamboj

    Ankur Kamboj New Member

    Joined:
    Jun 19, 2011
    Messages:
    7
    Likes Received:
    0
    Trophy Points:
    0
    main()
    {
    int *p,*q,i;
    p=(int *)100;
    q=(int *)200;
    i=q-p;
    printf("%d",i);
    }
    it is getting output 50 in turbo c compiler.I do not know how it is working please reply me...:confused:
     
  2. shabbir

    shabbir Administrator Staff Member

    Joined:
    Jul 12, 2004
    Messages:
    15,287
    Likes Received:
    364
    Trophy Points:
    83
    Garbage value because it is actually subtracting the value stored at location 200 and 100 and not 200 and 100.
     
  3. xpi0t0s

    xpi0t0s Mentor

    Joined:
    Aug 6, 2004
    Messages:
    3,012
    Likes Received:
    203
    Trophy Points:
    0
    Occupation:
    Senior Support Engineer
    Location:
    England
    No, C doesn't dereference pointers unless you use *, i.e. you would get the difference between the contents if you did
    Code:
    i = *q - *p;
    
    The reason you don't get 100 is because C takes the size of things pointed to into account. Turbo C is dead ancient so probably ints are 2 bytes, so if you subtract two int* pointers from each other with a difference of 100 bytes you get 50, because you can only store 50 ints in 100 bytes. That's how pointers work. If you want to subtract 100 from 200 and get 100, then use integers.

    Do this:
    Code:
    printf("%d",sizeof(int));
    
    to confirm whether or not ints really are 2 bytes.
     
  4. poornaMoksha

    poornaMoksha New Member

    Joined:
    Jan 29, 2011
    Messages:
    150
    Likes Received:
    33
    Trophy Points:
    0
    Occupation:
    Software developer
    Location:
    India
    Yup, I agree with xpi0t0s
    On My Linux box, the output was 25 since on my machine int captures 4 bytes
     
  5. sura

    sura Banned

    Joined:
    Aug 4, 2011
    Messages:
    47
    Likes Received:
    1
    Trophy Points:
    0
    Location:
    India,Tamil Nadu.
    in linux (gcc) the memory for int is 4.............
    in turbo c the memory for int is 2............
    i want to know which is the standard one declared by ANCI ....................
     

Share This Page