Is empty array in the end of the structure a C standard?

梦想与她 提交于 2021-02-17 05:25:19

问题


I have noticed that an empty array in the end of the structure is often used in open source projects:

typedef struct A
{
    ......
    void *arr[];
} A;  

I want to know is this a C standard? Or only OK for gcc compiler?


回答1:


As of C99, it is now a C standard. Pre-C99 compilers may not support it. The old approach was to declare a 1-element array, and to adjust the allocation size for that.

New way:

typedef struct A
{
    ......
    void *arr[];
} A;  

int slots = 3;
A* myA = malloc(sizeof(A) + slots*sizeof(void*));
myA->arr[2] = foo;

Old way:

typedef struct A
{
    ......
    void *arr[1];
} A;  

int slots = 3;
A* myA = malloc(sizeof(A) + (slots-1)*sizeof(void*));
myA->arr[2] = foo;



回答2:


The standard (draft N1570) 18 of 6.7.2.1, states:

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.



来源:https://stackoverflow.com/questions/22220263/is-empty-array-in-the-end-of-the-structure-a-c-standard

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!