title: How does an array of structures with flexible array members behave?
body: <p>As the title states I was wondering how arrays of C-structs with a <a href="https://en.wikipedia.org/wiki/Flexible_array_member" rel="nofollow">flexible array member</a> behaves. Here is an example:</p>
  
  <pre><code>struct vector {
      size_t length;
      double array[];
  };
  </code></pre>
  
  <p>The Wikipedia article says: </p>
  
  <blockquote>
    <p>The <code>sizeof</code> operator on such a struct is required to give the offset of the flexible array member.</p>
  </blockquote>
  
  <p>On my machine this corresponds to 8 bytes (<code>sizeof(size_t)</code>). But what happens, when I do the following:</p>
  
  <p>Obviously the array cannot hold the data of vector <code>v0</code>, since it's only <i>3*8 bytes = 24 bytes</i> wide. How can I deal with situations like this?</p>
  
  <pre><code>#define LENGTH 10
  
  int main() {
      struct vector arr[3];
  
      struct vector *v0 = calloc(1, sizeof(*v0) + LENGTH * sizeof(v0-&gt;array[0]));
      v0-&gt;length = LENGTH;
  
      size_t i;
      for (i = 0; i &lt; v0-&gt;length; i++) {
          v0-&gt;array[i] = (double) i;
      }
  
      struct vector v1;
      struct vector v2;
  
      arr[0] = *v0;
      arr[1] =  v1;
      arr[2] =  v2;
  
      for (i = 0; i &lt; arr[0].length; i++) {
          printf("arr[0].array[%2zu] equals %2.0lf.\n", i, arr[0].array[i]);
          printf("    v0-&gt;data[%2zu] equals %2.0lf.\n", i, v0-&gt;array[i]);
      }
      return 0;
  }
  </code></pre>
  
  <p>For example, when I'm writing a library (header: <code>mylib.h</code>, source: <code>my lib.c</code>) and want to hide the implementation of one specific struct from the user (struct declared in header, defined in source - hidden). Sadly exactly this struct contains a flexible array member. Won't this lead to unexpected behavior, when the user tries to create an array of named structures?</p>
  
  <p><strong>Extra</strong>: Read more about the flexible array in the <a href="http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1124.pdf" rel="nofollow">OpenSTD C Spec</a>. <br>Just search for '<em>flexible array member</em>'.</p>
  
  <p><strong>EDIT</strong>: The latest draft of the C11 Standard, the most up to date freely available reference for the C language is available here: <a href="http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf" rel="nofollow">http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf</a></p>