gpt4 book ai didi

c - 零元素数组需要什么?

转载 作者:行者123 更新时间:2023-11-30 17:14:31 25 4
gpt4 key购买 nike

在Linux内核代码中我发现了以下我无法理解的东西。

 struct bts_action {
u16 type;
u16 size;
u8 data[0];
} __attribute__ ((packed));

代码在这里:http://lxr.free-electrons.com/source/include/linux/ti_wilink_st.h

零元素数据数组的需求和用途是什么?

最佳答案

这是一种获得可变大小数据的方法,而无需调用 malloc(本例中为 kmalloc)两次。你可以像这样使用它:

struct bts_action *var = kmalloc(sizeof(*var) + extra, GFP_KERNEL);

这曾经不是标准的,被认为是一种 hack(正如 Aniket 所说),但它在 C99 中标准化。现在它的标准格式是:

struct bts_action {
u16 type;
u16 size;
u8 data[];
} __attribute__ ((packed)); /* Note: the __attribute__ is irrelevant here */

请注意,您没有提及 data 字段的任何大小。另请注意,此特殊变量只能出现在结构的末尾。

<小时/>

在C99中,这个问题在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. 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.

或者换句话说,如果您有:

struct something
{
/* other variables */
char data[];
}

struct something *var = malloc(sizeof(*var) + extra);

您可以使用[0, extra)中的索引访问var->data。请注意,sizeof(struct Something) 只会给出其他变量的大小,即为 data 提供 0 的大小。

<小时/>

注意到该标准实际上如何给出malloc这样的构造的示例(6.7.2.1.17)可能也很有趣:

struct s { int n; double d[]; };

int m = /* some value */;
struct s *p = malloc(sizeof (struct s) + sizeof (double [m]));

同一位置的标准的另一个有趣的注释是(强调我的):

assuming that the call to malloc succeeds, the object pointed to by p behaves, for most purposes, as if p had been declared as:

struct { int n; double d[m]; } *p;

(there are circumstances in which this equivalence is broken; in particular, the offsets of member d might not be the same).

关于c - 零元素数组需要什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30278476/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com