title: Padding in structures in C
body: <p>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.</p>
  
  <p>Suppose you are given two structures as:</p>
  
  <pre><code>struct A {  
    int* a;  
    char b;  
   }  
  </code></pre>
  
  <p>and , </p>
  
  <pre><code>struct B {  
    char a;  
    int* b;  
  }  
  </code></pre>
  
  <p>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.   </p>
  
  <p>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</p>
  
  <p>Please help me with the answers.</p>