gpt4 book ai didi

c - flexible array member not at end of struct错误的原因是什么?

转载 作者:太空狗 更新时间:2023-10-29 16:28:36 24 4
gpt4 key购买 nike

我想知道为什么我在调用 malloc 时一直收到 error: flexible array member not at end of struct 错误。我有一个带有可变长度数组的结构,但我一直收到此错误。

结构是,

typedef struct {
size_t N;
double data[];
int label[];
} s_col;

对 malloc 的调用是,

col = malloc(sizeof(s_col) + lc * (sizeof(double) + sizeof(int)));

这是对 malloc 的正确调用吗?

最佳答案

一个结构体中只能有一个灵活的数组成员,而且它必须始终是结构体的最后一个成员。换句话说,在这种情况下,您在调用 malloc 之前就出错了,以至于实际上没有办法为此结构正确调用 malloc

做你想做的事情(相同数量的 datalabel 成员的数组),你可以考虑这样的事情:

struct my_pair { 
double data;
int label;
};

typedef struct {
size_t N;
struct my_pair data_label[];
};

请注意,尽管这有些不同:它给您的不是 double 数组后跟 int 数组,而是一个 数组double 后跟一个 int,然后是下一个 double,下一个 int,依此类推。这是否足够接近相同将取决于您如何使用数据(例如,为了传递给需要连续数组的外部函数,您可能必须以不同的方式做事)。

关于c - flexible array member not at end of struct错误的原因是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11180378/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com