[英]Getting the size of the type of a zero-length array element in a structure
Maybe the title is confusing, but the idea is simple.也许标题令人困惑,但想法很简单。 Given the following structure:
给定以下结构:
struct z {
uint64_t _a;
uint64_t _b;
struct {
char _c[64];
uint64_t _d;
} data[0];
} __attribute__((packed));
How might one get the size of the type of the anonymous inner struct data
?如何获得匿名内部结构
data
类型的大小? I do not want to name the struct and clutter the namespace, but I do need its size when computing the total length of what a serialized buffer would look like with a non-zero data
trailer.我不想命名结构并使命名空间混乱,但在
data
序列化缓冲区的总长度时,我确实需要它的大小。
If you try this you'll find something similar to:如果你尝试这个,你会发现类似的东西:
struct z *p;
sizeof(struct z) == 16
sizeof(*p) == 16
sizeof(p->data) == 0
These results are expected.这些结果是预期的。 However, what I was hoping to see was the following:
但是,我希望看到的是以下内容:
sizeof(typeof(p->data)) == 72
But, unfortunately, I still get但是,不幸的是,我仍然得到
sizeof(typeof(p->data)) == 0
I thought it might be because the struct was unnamed, but after providing it with a name you'll find the earlier results are still true.我认为这可能是因为该结构未命名,但在为其提供名称后,您会发现早期的结果仍然正确。
Is there a way to get the size of an anonymous inner zero-length structure?有没有办法获得匿名内部零长度结构的大小?
I would use:我会使用:
sizeof(p->data[0])
Because it's inside sizeof
and therefore not evaluated, p->data[0]
does not actually dereference p->data
.因为它在
sizeof
内部,因此没有被评估,所以p->data[0]
实际上并没有取消引用p->data
。 The compiler only figures out the type.编译器只计算出类型。
but I do need its size when computing the total length of what a serialized buffer would look like with a non-zero data trailer
但是在计算带有非零数据预告片的序列化缓冲区的总长度时,我确实需要它的大小
You can't do that with sizeof()
.你不能用
sizeof()
做到这一点。 You must keep track of the size yourself.您必须自己跟踪大小。
Per the GCC documentation (bolding mine - and note it well):根据 GCC 文档(我的粗体字 - 请注意):
Declaring zero-length arrays is allowed in GNU C as an extension.
在 GNU C 中允许声明零长度 arrays 作为扩展。 A zero-length array can be useful as the last element of a structure that is really a header for a variable-length object:
零长度数组可用作结构的最后一个元素,该结构实际上是 header,用于可变长度 object:
struct line { int length; char contents[0]; }; struct line *thisline = (struct line *) malloc (sizeof (struct line) + this_length); thisline->length = this_length;
Although the size of a zero-length array is zero , an array member of this kind may increase the size of the enclosing type as a result of tail padding.
尽管长度为零的数组的大小为零,但由于尾部填充,这种数组成员可能会增加封闭类型的大小。 ...
...
Note how the example code keeps track of the number of elements in the array.请注意示例代码如何跟踪数组中的元素数量。
just name it.只是命名它。 if instead of saying
如果不是说
struct {
char _c[64];
uint64_t _d;
} data[0];
you say你说
struct data {
char _c[64];
uint64_t _d;
} data[0];
then sizeof(struct data)
will tell you it's sizeof.然后
sizeof(struct data)
会告诉你它的 sizeof。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.