boot2

Playing with the boostrap
git clone https://git.ryansepassi.com/git/boot2.git
Log | Files | Refs | README

077-flex-array.c (605B)


      1 /* §L.1 flexible array member.
      2  *
      3  * `int data[]` as the last field of a struct: sizeof excludes the
      4  * trailing array, but accessing `s->data[i]` yields the right element
      5  * by treating data[] as a pointer to memory immediately after the
      6  * named fields.
      7  *
      8  * We back the struct with a plain int[] buffer and reinterpret-cast
      9  * to avoid depending on flex-aware initializer syntax.
     10  *
     11  * Expected: 3 + 10 + 20 + 30 = 63.
     12  */
     13 
     14 struct s { int n; int data[]; };
     15 
     16 int buf[] = { 3, 10, 20, 30 };
     17 
     18 int main(void) {
     19     struct s *p = (struct s *)buf;
     20     return p->n + p->data[0] + p->data[1] + p->data[2];
     21 }