title: Structure Alignment when Accessed by Pointer
body: <p>When accessing a structure from a byte stream (File, Network, etc...)
  what does alignment mean?</p>
  
  <p>For example, I can understand why a compiler would want to pad the following
  structure with extra bytes to align the int a and short b at word addresses (multiples of 4).  However, what does this mean when accessing memory at a 
  random address via using a pointer?  Does using the -> operator generate inefficient code? Or am I missing something?</p>
  
  <pre><code>typedef struct{
      void*   ptr;  //4 bytes
      char    c1;   //1 byte
      int     a;    //4 bytes
      char    c2;   //1 byte
      short   b;    //2 byte
      char    c3;   //1 byte
  } Odd_Struct;     //Minimum needed = 13 bytes, actual (with padding) = 20
  
  unsigned char buffer[128];
  Odd_Struct odd_struct;
  
  odd_struct.a = 123456789;
  odd_struct.b = 12345;
  
  printf("sizeof(odd_struct): %d\n", sizeof(Odd_Struct));
  
  memcpy(buffer+3, &amp;odd_struct, sizeof(Odd_Struct));
  
  Odd_Struct* testPtr = (Odd_Struct*)(buffer+3);
  
  printf("testPtr-&gt;a: %d\n", testPtr-&gt;a);
  printf("testPtr-&gt;b: %d\n", testPtr-&gt;b);
  </code></pre>
  
  <p>And the output</p>
  
  <pre><code>sizeof(odd_struct): 20
  testPtr-&gt;a: 123456789
  testPtr-&gt;b: 12345
  </code></pre>
  
  <p>To answer why I would want to do this:</p>
  
  <p>I am intending to use a system with very limited RAM, so it's tempting
  to just cast a byte (unsigned char) pointer to a struct pointer and access it
  that way.  Without an additional copy of memory.  I.E. use the bytes in place.
  This is working fine on a x86 PC using gcc.  But based on comments below, this seems like it might be a bad idea.</p>