Array of variable length in struct

后端 未结 3 1367
失恋的感觉
失恋的感觉 2020-12-09 00:31

I\'ve created 2 structures to represent images (a pixel and an image one) in C.

typedef struct pixel {
    unsigned char red;
    unsigned char green;
    un         


        
3条回答
  •  生来不讨喜
    2020-12-09 00:56

    You are using what is called a variable length array, however, there's a problem. In C every struct must have a specific byte length, so that, for example, sizeof(struct image) can be evaluated. In your case, the variable length array's size cannot be determined at compile time, so it is illegal.

    On another note, you probably want pointers there, instead of arrays of declared length:

    typedef struct image
    {
        int width;
        int heigth;
        struct pixel **pixels;
    };
    

    Disclaimers: VLAs in structs are occasionally allowed, although it's a matter of opinion if this extension is more of a bug than a feature. See: Undocumented GCC Extension: VLA in struct

    Edit: remyabel points out the GCC docs that talk about the rare situations in which VLAs in structs are okay: https://gcc.gnu.org/onlinedocs/gcc/Variable-Length.html#Variable-Length

提交回复
热议问题