【发布时间】:2020-05-06 23:50:21
【问题描述】:
我想要一个可变大小的结构,但我想将具有一定大小的结构的实例嵌入到另一个结构中。想法是这样的:
struct grid {
size_t width, height;
int items[ /* width * height */ ];
};
struct grid_1x1 {
size_t width, height;
int items[1];
};
struct grid_holder {
struct grid_1x1 a, b;
};
int main(void)
{
struct grid_holder h = {
.a = { .width = 1, .height = 1, .items = { 0 } },
.b = { .width = 1, .height = 1, .items = { 0 } },
};
struct grid *a = (struct grid *)&h.a, *b = (struct grid *)&h.b;
}
如果我的所有代码都假定struct grid 的items 成员具有width * height 元素,那么可以像上面那样转换a 和b 吗?
换句话说,一个元素的灵活数组成员是否总是与一个元素的固定大小的数组成员具有相同的偏移量和大小,假设结构在其他方面是相同的?我想要一个基于 C99 标准的答案。如果偏移量可能不同,是否有其他方法可以实现我在开头所述的目标?
【问题讨论】: