Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Only one array without a size allowed per struct?

I was writing a struct to describe a constant value I needed, and noticed something strange.

namespace res{
    namespace font{
        struct Structure{
            struct Glyph{
                int x, y, width, height, easement, advance;
            };
            int glyphCount;
            unsigned char asciiMap[];   // <-- always generates an error
            Glyph glyphData[];          // <-- never generates an error
        };
        const Structure system = {95, 
                              {
                                 // mapping data
                              }, 
                              {
                                 // glyph spacing data
                              }
        }; // system constructor
    } // namespace font
} // namespace res

The last two members of Structure, the unsized arrays, do not stop the compiler if they are by themselves. But if they are both included in the struct's definition, it causes an error, saying the "type is incomplete"

This stops being a problem if I give the first array a size. Which isn't a problem in this case, but I'm still curious...

My question is, why can I have one unsized array in my struct, but two cause a problem?

like image 833
Anne Quinn Avatar asked Dec 20 '12 11:12

Anne Quinn


1 Answers

In standard C++, you can't do this at all, although some compilers support it as an extension.

In C, every member of a struct needs to have a fixed position within the struct. This means that the last member can have an unknown size; but nothing can come after it, so there is no way to have more than one member of unknown size.

If you do take advantage of your compilers non-standard support for this hack in C++, then beware that things may go horribly wrong if any member of the struct is non-trivial. An object can only be "created" with a non-empty array at the end by allocating a block of raw memory and reinterpreting it as this type; if you do that, no constructors or destructors will be called.

like image 108
Mike Seymour Avatar answered Sep 28 '22 23:09

Mike Seymour