title: Padding in a struct
body: <p>I know there is <strong><a href="https://stackoverflow.com/questions/119123/why-isnt-sizeof-for-a-struct-equal-to-the-sum-of-sizeof-of-each-member">padding in struct</a></strong> (<a href="https://stackoverflow.com/questions/5397447/struct-padding-in-c">example from this post</a>)</p>
  
  <pre><code> struct A   --&gt;8 bytes
   {
      char c;
      char d;
   //2 padding here
      int i;
   };
   struct B  --&gt;12 bytes
   {
       char c;
   //3 padding here
      int i;
      char d;
   //3 padding here
   };
  </code></pre>
  
  <p>Now, I don't understand following example:</p>
  
  <pre><code> typedef struct {  --&gt;**shouldn't it be 12 bytes**
      int a;
      char *str;
   } TestS;
  
   TestS s;
  
  int main(int argc, char *argv[]) {
  
     printf("An int is %lu bytes\n", sizeof( int )); --&gt;4
     printf("A Char * is %lu bytes\n", sizeof( char *)); --&gt;8
     printf("A double is %lu bytes\n", sizeof( double )); --&gt;8
  
     printf("A struct is %lu bytes\n", sizeof s); --&gt;why 16?
  
     return 0;
  
   }
  </code></pre>
  
  <p>First I thought it may <strong>aligning to 8*N byte</strong> (for I use <strong>ubuntu-64</strong>), so I try more structs.</p>
  
  <pre><code>  typedef struct {
     int i;
     char *str;
    } stru_12;
  
  
    typedef struct {
      int i;
      char *str;
      char c;
    } stru_13;
  
   typedef struct {
      int i;
      char str[7];
   } stru_11;
  
   typedef struct {
     char *str;
     double d;
   } stru_16;
  
    stru_12 test12;
    stru_13 test13;
    stru_11 test11;
    stru_16 test16;
  
  int main (int argc, char *argv[]) {
      printf("A test12 is %lu bytes, address is %p\n", sizeof test12, &amp;test12);
      printf("A test13 is %lu bytes, address is %p\n", sizeof test13, &amp;test13);
      printf("A test11 is %lu bytes, address is %p\n", sizeof test11, &amp;test11);
      printf("A test16 is %lu bytes, address is %p\n", sizeof test16, &amp;test16);
  }
  </code></pre>
  
  <blockquote>
    <p>Result:</p>
    
    <p>A test12 is 16 bytes, address is 0x601060  </p>
    
    <p>A test13 is 24 bytes, address is 0x601090  </p>
    
    <p>A test11 is 12 bytes, address is 0x601080   </p>
    
    <p>A test16 is 16 bytes, address is 0x601070</p>
  </blockquote>
  
  <p>Sorry for being so long.</p>
  
  <p>My question is:</p>
  
  <ul>
  <li><p>Why test12 (int + char*) is 16 bytes and test13 (int + char * + char) is 24?(it seems that <strong>8*N</strong> is favored, but 12 bytes is allowed )</p></li>
  <li><p>Why the differences of the addresses of structs is 16 addressing unit (more padding?)?</p></li>
  </ul>
  
  <p>For your use:</p>
  
  <blockquote>
    <p>cache_alignment    : 64</p>
    
    <p>address sizes  : 36 bits physical, 48 bits virtual</p>
    
    <p>Ubuntu 14.04.1 LTS x86_64</p>
  </blockquote>