灵活数组成员不在结构体错误末尾的原因是什么? [英] What is the cause of flexible array member not at end of struct error?
问题描述
我想知道为什么我在调用 malloc 时总是收到 error: flexible array member not at end of struct
错误.我有一个带有可变长度数组的结构,但我不断收到此错误.
I am wondering why I keep getting error: flexible array member not at end of struct
error when I call malloc. I have a struct with a variable length array, and I keep getting this error.
结构是,
typedef struct {
size_t N;
double data[];
int label[];
} s_col;
对 malloc 的调用是,
and the call to malloc is,
col = malloc(sizeof(s_col) + lc * (sizeof(double) + sizeof(int)));
这是对 malloc 的正确调用吗?
Is this the correct call to malloc?
推荐答案
一个结构体中只能有一个灵活的数组成员,并且它必须始终是结构体的最后一个成员.换句话说,在这种情况下,您在调用 malloc
之前就出错了,以至于实际上无法为此结构正确调用 malloc
.
You can only have one flexible array member in a struct, and it must always be the last member of the struct. In other words, in this case you've gone wrong before you call malloc
, to the point that there's really no way to call malloc
correctly for this struct.
要执行您似乎想要的操作(具有相同数量的 data
和 label
成员的数组),您可以考虑以下内容:
To do what you seem to want (arrays of the same number of data
and label
members), you could consider something like:
struct my_pair {
double data;
int label;
};
typedef struct {
size_t N;
struct my_pair data_label[];
};
请注意,这有点不同:它不是一个 double
数组,后面跟着一个 int
数组,而是一个 数组double
后跟一个 int
,然后是下一个 double
,下一个 int
,依此类推.这是否足够接近相同取决于您如何使用数据(例如,为了传递给需要连续数组的外部函数,您可能必须以不同的方式做事).
Note that this is somewhat different though: instead of an array of double
s followed by an array of int
s, it gives you an array of one double
followed by one int
, then the next double
, next int
, and so on. Whether this is close enough to the same or not will depend on how you're using the data (e.g., for passing to an external function that expects a contiguous array, you'll probably have to do things differently).
这篇关于灵活数组成员不在结构体错误末尾的原因是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!