Interview Question
Country: United States
Interview Type: Phone Interview
Hey, why you are taking 4bits instead of 1 byte..... like, according to my understanding representation of 300 in little endian would be,
0x12345678 - 0010 1100
0x12345679 - 0000 0001
0x1234567a - 0000 - 0000
0x1234567b - 0000 - 0000
Correct me if I am wrong. Although it will not affect the end result :)
And can you please explain for big endian also??
The memory layout canbe also like what you have pointed out.This will be for Big Endian machine where higher Byte value goes to lower byte position or address and Lower Byte Value to lower byte position or address.
Like
0x56677788 is the address of an int having the space for 8 bits
_ _ _ _ _ _ _ _
First four will be for the place for the lower byte value for little endina machine and for higher value like 0010 as you have pointed out !
First, you will have to cast the pointer to int (&i) to a pointer to char (char*). As soon as you do it and increment it, you will be addressing the byte #1 (second byte) of the original int. So, the actual output will depend on the size of int and the endianness of the machine this code is compiled for.
it will print 300.
he is updating next memory
i=300 ->2000
*p=300
++p->2004
*p=2->2004
printf("%d",i)->2000 ====300
I think it will give error, because first it is pointing to an allocated location, after that it is trying to point to next location and try to assign a value into it which is not allocated yet.
If most significant byte stores first then it will print 256, or if least significant byte stores first then it will print 556.
i = 300;
- softy June 06, 2012=> i = 100101100 //in binary in word format => B B Hb 0001 0010 1100 where B = Byte and Hb = Half Byte
(A)=> in memory (assuming it is Little endian))
0x12345678 - 0010- 1100
0x12345679 - 0000- 0001
0x1234567a - 0000 - 0000
0x1234567b - 0000 - 0000
0x1234567c - Location of next intezer(location of ptr++ or ptr + 1 where ptr is an intezer pointer as ptr is of type int => on doing ++ptr it will increment by 4 byte(**size of int**))
when
(B)we do char *ptr = &i;
ptr will become of type char => on doing ++ptr it will increment by 1 byte(**size of char**)
so on doing ++ptr it will jump to location -> 0x12345679 (which has 0000- 0001)
now we are doing
*++ptr = 2
=> 0x12345679 will be overwritten by 2 => 0x12345679 will have 00**10** - 0000 instead of 000**1** - 0000
so the new memory content will look like this :
(C)0x12345678 - 0010 - 1100
0x12345679 - 0000- 0010
0x1234567a - 0000 - 0000
0x1234567b - 0000 - 0000
which is equivalent to => B B Hb 0010 00101100 where B = Byte and Hb = Half Byte
=> 556