当前位置 : 主页 > 编程语言 > c++ >

为什么允许在struct中定义未定义的大小数组?

来源:互联网 收集:自由互联 发布时间:2021-06-23
当我编写以下代码时,我得到了预期的错误错误:’data’中缺少数组大小. int main(){ unsigned char data[]; return 0;} 但是,当我运行相同的代码但将有问题的行包装在结构中时,没有错误. typedef
当我编写以下代码时,我得到了预期的错误错误:’data’中缺少数组大小.

int main()
{
    unsigned char data[];

    return 0;
}

但是,当我运行相同的代码但将有问题的行包装在结构中时,没有错误.

typedef struct credit_card_s
{
  unsigned char is_valid;

  unsigned char data[];

} credit_card_t;

任何人都可以向我解释为什么允许这样做?

后者被称为 “flexible array member”,这是结构的特例.允许结构的最后一个成员没有大小.

As a special case, the last element of a structure with more than one named member may have an incomplete array type; this is called a flexible array member. In most situations, the flexible array member is ignored. In particular, the size of the structure is as if the flexible array member were omitted except that it may have more trailing padding than the omission would imply. However, when a . (or ->) operator has a left operand that is (a pointer to) a structure with a flexible array member and the right operand names that member, it behaves as if that member were replaced with the longest array (with the same element type) that would not make the structure larger than the object being accessed; the offset of the array shall remain that of the flexible array member, even if this would differ from that of the replacement array. If this array would have no elements, it behaves as if it had one element but the behavior is undefined if any attempt is made to access that element or to generate a pointer one past it.

另见example 20.

前者是一个普通的数组,不允许零大小.见6.7.6.2 Array declarators.

If they delimit an expression (which specifies the size of an array), the expression shall have an integer type. If the expression is a constant expression, it shall have a value greater than zero. In other words, the language standard says so.

网友评论