什么是灵活的数组成员的原因不是结构错误的结束? [英] What is the cause of flexible array member not at end of struct error?

查看:354
本文介绍了什么是灵活的数组成员的原因不是结构错误的结束?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很奇怪,为什么我总是收到错误:灵活的数组成员没有出现在结构错误的结束,当我调用malloc。我有一个可变长度的数组结构,和我不断收到此错误。

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.

要你好像有什么想(相同数量的数据标签成员的阵列),你可以考虑是这样的:

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[];
};

请注意,这是有所不同,但:不是数组双击紧随其后是 INT 的数组S,它给你的数组有一个双击后跟一个 INT ,那么接下来的,一个 INT ,等等。这是否是足够接近相同与否将取决于你如何使用数据(例如,传递给需要一个连续的阵列外部函数,你可能需要做一些与众不同的事情)。

Note that this is somewhat different though: instead of an array of doubles followed by an array of ints, 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆