Thread: Int and short

    #1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2013
    Posts
    3
    Rep Power
    0

    Int and short


    I was following a web lecture programming paradigm CS107 and during the lecture the professor wrote the following code

    Code:
       int arr[5];
         arr[3]=128;
         ((short *) arr)[6]=2;
         cout<<arr[3]<<endl;
    output = 640 (as claimed by the professor)

    professor claim:

    "Each int is composed of 4 bytes, Each short is composed of 2 bytes. The second and third statement above actually set the same bytes in memory. arr[3] sets the memory 12 bytes over (3 *4 (size of int)=12). ((short *)arr[6]) (6*2(size of short)=12) also sets the memory six bytes over. Although, 128 fits in the 15th and 16th bytes, while 2 is placed in the 13th byte. When arr[3] is printed to the scree, the value printed out is 128+512=640 (2^9+2^7=640). "

    but when I run the code in windows intel machine then the output is 2 .

    Is there anything professor missed or ???

    with regards,
    Faisal.
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jan 2013
    Posts
    159
    Rep Power
    19
    What compiler are you using?


    Jim
  4. #3
  5. Contributed User
    Devshed Specialist (4000 - 4499 posts)

    Join Date
    Jun 2005
    Posts
    4,379
    Rep Power
    1871
    > Although, 128 fits in the 15th and 16th bytes, while 2 is placed in the 13th byte.
    Your prof seems to be assuming that the machine is big-endian.

    On a little endian machine, things are different.
    Code:
    (gdb) run
    Starting program: /home/sc/Documents/a.out 
    
    Breakpoint 1, main () at foo.cpp:4
    4	   int arr[5] = { -1,-1,-1,-1,-1 };
    (gdb) s
    5	     arr[3]=128;
    (gdb) x/16xb arr
    0x7fffffffe110:	0xff	0xff	0xff	0xff	0xff	0xff	0xff	0xff
    0x7fffffffe118:	0xff	0xff	0xff	0xff	0xff	0xff	0xff	0xff
    (gdb) s
    6	     ((short *) arr)[6]=2;
    (gdb) x/16xb arr
    0x7fffffffe110:	0xff	0xff	0xff	0xff	0xff	0xff	0xff	0xff
    0x7fffffffe118:	0xff	0xff	0xff	0xff	0x80	0x00	0x00	0x00
    (gdb) s
    7	     cout<<arr[3]<<endl;
    (gdb) x/16xb arr
    0x7fffffffe110:	0xff	0xff	0xff	0xff	0xff	0xff	0xff	0xff
    0x7fffffffe118:	0xff	0xff	0xff	0xff	0x02	0x00	0x00	0x00
    (gdb)
    I initialised your array to -1, then single-stepped the code and printed the raw bytes of the array at every step.

    The line printed by the s (single step) command is the line that is about to be executed.
    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

IMN logo majestic logo threadwatch logo seochat tools logo