c - C中的嵌套动态结构?

标签 c arrays data-structures struct

是否可以在一个结构中有两个灵活大小的数组?

我知道我可以做如下的事情

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/

相关文章:

javascript - 针对所有另一个数组过滤数组

java - 如何将字符串分成字符数组

python - 在一条消息中分离 AES/CBC IV 和密文

c - 关于pthread_join函数的问题

javascript - Math.min 和 Math.max 超出了最大调用堆栈大小

java - 使用哪个阵列?

c - j+=i 的 O 表示法

c - 发送方和接收方的不同 MPI_Datatypes

使用 cygwin : invalid argument 在 c 中编译 GTK-app

c - 如何将C游戏移植到浏览器