title: How does memory alignment work for a reference to a struct in C++?
body: <p>I made a discovery which I was not aware of when casting a buffer to a struct reference which itself includes a data buffer. </p>
  
  <p>I think this example is best explained with a code example:</p>
  
  <pre><code>struct myStruct {
    int a;
    int b;
    char data[1];
  };
  
  #define TB_SIZE 5
  char data[TB_SIZE] = {0x1, 0x2, 0x3, 0x4, 0x5};
  
  
  void f(struct myStruct&amp; dest) {
    dest.a = 33;
    memcpy(dest.data, data, TB_SIZE);
  }
  
  int main() {
    char buf[100];
    f(reinterpret_cast&lt;struct myStruct&amp;&gt;(buf[0]));
    struct myStruct castStruct = reinterpret_cast&lt;struct myStruct&amp;&gt;(buf[0]);
  
    printf("Src Values\n");
    for(int i = 0; i &lt; TB_SIZE; ++i) {
      printf("0x%02x, ", data[i]);
    }
    printf("\nActual\n");
    for(int i = 0; i &lt; TB_SIZE; ++i) {
      printf("0x%02x, ", castStruct.data[i]);
    }
  
  
    return 0;
  }
  </code></pre>
  
  <p>The output from this simple program is:</p>
  
  <pre><code>Src Values
  0x01, 0x02, 0x03, 0x04, 0x05, 
  Actual
  0x01, 0x02, 0x03, 0x04, 0x00,
  </code></pre>
  
  <p>After casting the buffer to a struct reference, when i print the data buffer inside the struct, it seems that we have lost the last value, ie. castStruct[4].</p>
  
  <p>Now I guess this has with alignment issues with structs to do but I am not really sure why. If I instead change all reference to pointers the program works as expected, Also if I just have one integer in myStruct before the data[] field the program also works as expected. So my question is simply, how does memory alignment work for a reference to a struct in C++?</p>