Return structure with flexible array member

后端 未结 7 1842
栀梦
栀梦 2021-01-15 03:23

I need to return a structure with a flexible array member from a C function but can\'t figure out why it doesn\'t compile. I know that returning arrays can be achieved by en

相关标签:
7条回答
  • 2021-01-15 04:18

    Structs with flexible array members like yours (where the size of data is not given in the struct definition) are to be allocated like that:

    struct data_array *a;   // pointer!!
    a = malloc( sizeof(struct data_array) + 1000 * sizeof(double) );
    

    Where sizeof(struct data_array) is the constant size of your struct excluding data and 1000 is the desired array size. Of course changing data to be a pointer and allocating it seperately will also work, but that is something slightly different.

    0 讨论(0)
提交回复
热议问题