1

In a library for binary messaging, I have some structs like these:

struct __attribute__((__packed__)) Header {
    int16_t msg_type;
    int16_t msg_size;
    char payload[];
};

struct __attribute__((__packed__)) SomeMessage {
    static const int value MsgType = 42;

    int64_t field1;
    int32_t field2;
    // ...
};

For writing the messages, I can make a packed type containing the two:

struct __attribute__((__packed__)) WriteMessage {
    Header hdr;
    SomeMessage body;
};

And this works - the size of the type and the alignments of all the fields is as I would want it to be. GCC gives me a warning, but otherwise works:

warning: ISO C++ forbids zero-size array ‘payload’ [-pedantic]

But why does it work? Effectively, char payload[] took zero space - isn't that disallowed? Am I relying on undefined behavior that happens to do something sensible?

Barry
  • 286,269
  • 29
  • 621
  • 977
  • 1
    It is an [extension](http://stackoverflow.com/a/26209437/1708801) – Shafik Yaghmour Feb 27 '15 at 16:08
  • It's a C language feature, which some C++ compilers support as an extension. You have to make sure there's enough memory for the structure and the array; as long as you do that, you can just treat it as an array of whatever size you want. – Mike Seymour Feb 27 '15 at 16:17

0 Answers0