Thread: what is its o/p and why?

  1. #1
    Registered User
    Join Date
    May 2007
    Posts
    3

    Question what is its o/p and why?

    Code:
    void main()
    {
       int *p,*q;
       p=(int*)1000;
       q=(int*)2000;
       printf("%d",(q-p));
    }
     
         why it outputs 500.anyone know the reason??help me

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    A much safer version which doesn't rely on undefined pointer behaviour.
    Code:
    #include <stdio.h>
    int main ( ) { /* Verily, main doest always return an int */
        int arr[100];
        int *p = &arr[10];
        int *q = &arr[40];
        printf("&#37;d\n",(q-p));
        return 0;
    }
    Then try this one
    Code:
    #include <stdio.h>
    int main ( ) { /* Verily, main doest always return an int */
        double arr[100];
        double *p = &arr[10];
        double *q = &arr[40];
        printf("%d\n",(q-p));
        return 0;
    }
    Notice anything?
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Registered User
    Join Date
    Sep 2006
    Posts
    835
    On your box, int * is 2 bytes. So two addresses which are 1000 bytes apart are 500 int *'s apart.

  4. #4
    Woof, woof! zacs7's Avatar
    Join Date
    Mar 2007
    Location
    Australia
    Posts
    3,459
    See the FAQ regarding void main()... On my 32bit system (an int is 4 bytes) the result is 250, so the two addresses are 1000 bytes appart, or 4 * 250 bytes.

Popular pages Recent additions subscribe to a feed