Adobe Interview Question
Country: United States
Interview Type: Phone Interview
its doesn't matter how many fields in union is declare but they all share same memory i.e. just long enough to save biggest field in this case 40 bytes will be allocated as its size of union A
now value of 'y' which is 15 will be stored in same shared block now u access any data type it will print value 15(if it is int,floa,double or short ) otherwise it will print some garbage value
But when i replaced long int y[5] to char i[5]; and int x[5] to char x[5].
Then also the result is 15 and 15. So could you please tell me why?
To my knowledge it should print element stord in 1st bit //x[0], y[0].
Don't you think so?
@rasmirnjanbabu did u changed the format specifier in printf statement use %c then se what u get
because printf is designed for taking variable no of arguments so it NEVER CHECK WHAT FORMAT SPECIFIER YOU GAVE
if its %d it will print first 4 bytes iirespective of what variable you gave
Answer will depend on endian ness of machine. if it had been a little endian machine it would come 15,0
Lets take the Machine as Big Endian (Read from left to right)
- dilip kasana September 19, 2012and size of int as 4.
size of inner most Union D=max{size of char,size of int[5]} = 20 bytes ======5*sizeof(int)
size of Union C=max{size of int , size of Union D} = 20 bytes
size of Union B= max { size of double , size of Union C} =20 bytes
size of the whole Union=max {size of long int[5],size of Union B}= 5*sizeof(long int) = 20
if we store p->b.a.k= 15 in union
because it is an int so it will take first 4bytes and the whole 20 bytes will look as
000F 0000 0000 0000 0000 in Hexadecimal
So when reading p->b.a.s.x[0] as first int it will print 15
and reading p->y[0] as long int it will again print 15 because both are 4 byte.