Return structure with flexible array member

2020-03-27 17:41发布

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 encapsulating them in a struct as follows:

struct data_array {
    long length;
    double data[];
};

My function looks like this:

struct data_array test (int length) {
    struct data_array a;
    double* b = malloc (1000);
    a.length = 1000;
    a.data = b;
    return a;
}

However, the compiler returns: "invalid use of flexible array member".

According to the book "21st Century C", the data array in the struct is handled as a pointer (which makes perfectly sense to me). It has not been initialized and therefore there should be no memory been allocated for it to hold its data. (even the compiler doesn't know how much memory is needed for it). So I have to allocate the memory and assign it to my return variable.

So, why does the compiler returns an error? And how can I solve this problem?

7条回答
爷的心禁止访问
2楼-- · 2020-03-27 18:30

I use gcc and I think may be this way is ok:

struct data_array {
    long length;
    double* data;
};
struct data_array* test (int length) {
    struct data_array* a =(struct data_array *) malloc (sizeof (data_array));
    a->data = malloc (length*sizeof(double));
    a->length = length;
    return a;
}
查看更多
登录 后发表回答