Array of size 0 at the end of struct
<p>My professor of a systems programming course I'm taking told us today to define a struct with a zero-length array at the end:</p>

<pre><code>struct array{
    size_t size;
    int data[0];
};

typedef struct array array;
</code></pre>

<p>This is a useful struct to define or initialize an array with a variable, i.e., something as follows:</p>

<pre><code>array *array_new(size_t size){
    array* a = malloc(sizeof(array) + size * sizeof(int));

    if(a){
        a-&gt;size = size;
    }

    return a;
}
</code></pre>

<p>That is, using <code>malloc()</code>, we also allocate memory for the array of size zero. This is completely new for me, and it's seems odd, because, from my understanding, structs do not have their elements necessarily in continuous locations.</p>

<p>Why does the code in <code>array_new</code> allocate memory to <code>data[0]</code>? Why would it be legal to access then, say</p>

<pre><code>array * a = array_new(3);
a-&gt;data[1] = 12;
</code></pre>

<p>?</p>

<p>From what he told us, it seems that an array defined as length zero at the end of a struct is ensured to come immediately after the last element of the struct, but this seems strange, because, again, from my understanding, structs could have padding.</p>

<p>I've also seen around that this is just a feature of gcc and not defined by any standard. Is this true?</p>