This is an interview question. Till now, I used to think such questions were purely compiler dependent and shouldn't worry me, but now, I am rather curious about it.
Suppose you are given two structures as:
struct A {
int* a;
char b;
}
and ,
struct B {
char a;
int* b;
}
So which one would you prefer and why?
My answer went like this (though I was somewhat shooting in the dark) that the first structure should be preferred since the compiler allocates space for a structure in some multiples of the word size (which is the size of the pointer - 4 bytes on 32 bit machines and 8 bytes on 64 bit ones). So, for both the structures the compiler would allocate 8 bytes(assuming its a 32 bit machine). But, in the first case, the padding would be done after all my variables(i.e. after a and b). So even if by some chance, b gets some value that overflows and destroys my next padded bytes, but my a is still safe.
He didn't seemed much pleased and asked for one disadvantage of the first structure over the second. I didn't have much to say. :D
Please help me with the answers.
Question&Answers:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…