title: Misaligning pointers to save space: How to do this cleanly without UB?
body: <p>Consider I have a struct like this:</p>
  
  <pre><code>struct X{
      int* somePtr;
      uint16_t someCounter;
  }
  </code></pre>
  
  <p>I use this struct extensively in very huge arrays (hundreds of millions of <code>X</code>s). Since C++ aligns the pointer to an 8-byte boundary, the struct uses up 16 bytes. Without this alignment, the struct would only use 10 bytes which is what I want to achieve, because the extra 6 bytes really cost a lot of memory.</p>
  
  <p>So I tried this using char arrays and the union hack:</p>
  
  <pre><code>struct X{
      char somePtr[8];
      uint16_t someCounter;
  
      int* getPtr(){
          union U { int* ptr; char chars[8]; };
          U u;
          u.chars = somePtr;
          return u.ptr;
      }
  }
  </code></pre>
  
  <p>This yields the desired 10 byte struct. My question now is: What are the drawbacks of this approach? Does it trigger undefined behaviour? Is this the best way to achieve "packed" structs in C++11 or are there ones which are better/cleaner? Is using such packed structs a good idea if a have huge arrays of the <code>X</code> structs?</p>
  
  <p>My Platform is x86 linux, but it would be cool if the solution was fully portable.</p>