是否可以在一个结构中有两个灵活大小的数组?
我知道我可以做如下的事情
struct A {
int countB;
struct B[0];
}
但我的问题是我们可以做类似下面的事情吗?
struct A {
int countB;
struct B[0];
int countC;
struct C[0];
}
如果是,我们如何获得 countC 的偏移量?
如果上述情况很难实现,是否还有其他容易解决此类情况的方法?
最佳答案
不,每个数据结构不允许超过一个灵活大小的数组:
6.7.2.1.16: 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.
灵活数组成员必须是最后一个的原因是,否则无法计算偏移量(相对于struct
初始成员地址的字节数)对于灵活数组成员之后的任何成员。
在你的情况下,一个变通方法是可能的,代价是在灵活成员之前存储一个额外的指针,指向中
:C
的位置B
struct A {
int countB;
int countC;
struct some_struct *C;
struct some_struct B[0];
};
分配struct A
时,需要额外分配countB+countC
的大小。成员C
需要设置为B+countB
的地址。
关于c - C中的嵌套动态结构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35373785/