struct

时间:2015-12-17 10:18:02

标签: c++ c

在结构中定义具有0个元素的数组是否合法,或者编译器允许它作为副作用?例如:

typedef struct _my_str
{
  int    len;
  double total;
  double tax;
  int    items;
  double item_price[0];
} my_struct;

2 个答案:

答案 0 :(得分:2)

GCC允许zero length arrays作为struct的最后一名成员 ISO C99使用灵活的阵列成员

更改了此项
typedef struct _my_str
{
  int    len;
  double total;
  double tax;
  int    items;
  double item_price[]; // Flexible array member
} my_struct;  

请注意,这在C ++中无效。

答案 1 :(得分:2)

  1. 在C中,您可以使用变量数组成员,但仅作为struct的最后一个元素:所以在您的情况下,您可以使用double item_price[];作为最终struct元素。但请注意,此类struct不能是其他struct的成员;甚至不是最后的成员。

  2. 在C ++中,它在任何情况下都是不合法的。但std::vectorstd::array等替代方案已足够。