我想声明一个结构,里面有一个灵活的数组成员,然后在上面使用 sizeof()
。原型(prototype)是:
typedef struct
{
uint16_t length;
uint8_t array[][2];
} FLEXIBLE_t;
然后我声明它:
const FLEXIBLE_t test = {
.length = sizeof(test),
.array = { { 0, 1 },
{ 2, 3 },
{ 4, 5 },
{ 6, 7 },
{ 8, 9 } }
};
一切都编译正常 (GCC) 但是当我检查 test.length
时它的值为 2,即它只计算 uint16_t
的 length
本身。
如何在编译时计算结构的大小?看来编译器使用的是原型(prototype)而不是具体实例。
最佳答案
sizeof
忽略灵活数组成员,因为灵活数组成员在结构中不占用空间。
C11-§6.7.2.2/18
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. [...]
请注意,标准 C 不允许在您的代码中进行灵活的数组成员初始化。它将调用未定义的行为(参见§6.7.2.2 第 20 和 21 段)。虽然 GCC 允许将此作为 extension :
GCC allows static initialization of flexible array members. This is equivalent to defining a new structure containing the original structure followed by an array of sufficient size to contain the data.
关于c - 在具有灵活数组的结构的初始化中使用 sizeof 运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41923089/