简体   繁体   中英

Create variable sized arrays in a C typedef struct?

I want to set the size of bits when I create the struct so I can create different sized bitmaps but just writing bits[(length * height) - 1] doesn't work.

typedef struct {
    uint8_t length;
    uint8_t height;
    uint8_t bits[ *how?* ];
} Bitmap;

Bitmap BMP_1 = {
    14,
    14,
    {  *Bitmap*  }
};

Bitmap BMP_2 = {
    20,
    20,
    {  *Bitmap*  }
};

You can't do that – sorry.

C11 standard, §6.7.2.1 Structure and union specifiers

  • ¶3 : 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.

  • ¶9 : A member of a structure or union may have any complete object type other than a variably modified type. 123)

  • ¶18 : 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. However, when a . (or -> ) operator has a left operand that is (a pointer to) a structure with a flexible array member and the right operand names that member, it behaves as if that member were replaced with the longest array (with the same element type) that would not make the structure larger than the object being accessed; the offset of the array shall remain that of the flexible array member, even if this would differ from that of the replacement array. If this array would have no elements, it behaves as if it had one element but the behavior is undefined if any attempt is made to access that element or to generate a pointer one past it.

123) A structure or union cannot contain a member with a variably modified type because member names are not ordinary identifiers as defined in 6.2.3 .

The nearest you can get is to create a FAM (flexible array member) by defining uint8_t bits[]; as the last element of the structure. Now you must use dynamic memory allocation ( malloc() et al) to create an instance of the type:

Bitmap *bm = malloc(sizeof(*bm) + length * height * sizeof(bm->bits[0]));

The size cannot go into a typedef.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM