-2

Some struct with flexible array:

struct SomeArray { unsigned length; int array[]; };

This code gcc (ver. 4.9.2) compiling with no errors:

struct s1{ unsigned length; SomeArray some_array; const char * string; } ss1;

How this work?

rst256
  • 17
  • 4
  • gcc 4.8.2 produced compile error because `SomeArray` (note that not `struct SomeArray`) isn't defined. – MikeCAT Aug 15 '16 at 16:24
  • "How this work?" - Yes, how? Did you compile with warnings enabled? (I'd expect an error, though) – too honest for this site Aug 15 '16 at 16:24
  • Hmmm, it works because of GCC extension? http://melpon.org/wandbox/permlink/23zsb6490RslWhV9 – MikeCAT Aug 15 '16 at 16:25
  • 1
    @MikeCAT: That link does not work properly. Anyway, you are right. Another question without a [mcve]. – too honest for this site Aug 15 '16 at 16:27
  • Questions seeking debugging help ("why isn't this code working?") must include the desired behavior, a specific problem or error and the shortest code necessary to reproduce it in the question itself. Questions without a clear problem statement are not useful to other readers. See: How to create a Minimal, Complete, and Verifiable example. – too honest for this site Aug 15 '16 at 16:27
  • @dbush In the question you linked to, the struct with the FAM is also the last member of all the containing structs, so it still fits the restriction that the FAM is at the end of the struct. This question is about using it in the middle of a struct. – Barmar Aug 16 '16 at 00:46

1 Answers1

1

From the standard:

As a special case, the last element of a structure with more than one named member may have an incomplete array type; this is called a flexible array member. In most situations, the flexible array member is ignored. In particular, the size of the structure is as if the flexible array member were omitted except that it may have more trailing padding than the omission would imply.

This seems to be one of the situations where the flexible array member is ignored. So the size of ss1.some_array doesn't include space for ss1.some_array.array.

Barmar
  • 741,623
  • 53
  • 500
  • 612
  • 1
    There's the specific constraint in ¶3 of §6.7.2.1 (you quote from ¶18 in the same section), which says: _A structure or union shall not contain a member with incomplete or function type (hence, a structure shall not contain an instance of itself, but may contain a pointer to an instance of itself), except that the last member of a structure with more than one named member may have incomplete array type; such a structure (and any union containing, possibly recursively, a member that is such a structure) shall not be a member of a structure or an element of an array._ **Thou shalt not!** – Jonathan Leffler Aug 15 '16 at 23:48