具有灵活数组成员的常量结构

标签 c struct constants variable-length-array

请考虑以下两种结构:

typedef struct { 
    int num_data;
    char * name_data;
    int data[]; 
} part_t; 
typedef struct { 
    int num_parts;
    char * name_parts;
    part_t parts[]; 
} container_t; 

理想情况下,我可以像这样初始化一个容器:

const container_t container = { 
    2,
    "Name of first container", 
    { 
            { 4, "Name of first part", { 1, 2, 3, 4 } }, 
            { 5, "Name of first part", { 1, 2, 3, 4, 5 } } 
    } 
};

我的编译器说:“错误:初始化器太多”

最佳答案

ISO/IEC 9899:2011 §6.7.2.1 结构和 union 说明符

3 A structure or union shall not contain a member with incomplete or function type (hence, a structure shall not contain an instance of itself, but may contain a pointer to an instance of itself), except that the last member of a structure with more than one named member may have incomplete array type; such a structure (and any union containing, possibly recursively, a member that is such a structure) shall not be a member of a structure or an element of an array.

18 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.

问题在于您不能将具有灵活数组成员的结构嵌入到数组或其他结构中。您可以拥有指向此类结构的指针,但不能拥有此类结构的实例。

关于具有灵活数组成员的常量结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13713788/

相关文章:

c - SDL2 [优化] : is SDL_Surface->texture->copy faster than drawing on renderer?

C链表循环引用

c - OFFSETOF 宏结构字段

c++ - 临时绑定(bind)到聚合初始化结构成员的生命周期

C - 作为 void ptr 传递到 int 列表的 ptr 地址 - 使用 int 或 const int?

c++ - 常量问题

c - 返回 time_t 错误

c - 使用 while 循环在 C 中进行数据验证

c++ - CPP、WinAPI - WM_CREATE 从 lParam 获取 CREATESTRUCT* 的正确方法

C++ - 常量变量,这是一个正确的术语吗?