c - 在具有灵活数组的结构的初始化中使用 sizeof 运算符

标签 c arrays struct sizeof flexible-array-member

我想声明一个结构,里面有一个灵活的数组成员,然后在上面使用 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_tlength本身。

如何在编译时计算结构的大小?看来编译器使用的是原型(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/

相关文章:

c - 多维数组边缘/边界条件

javascript - 为什么 Array.prototype 只在控制台输出 [] ?

c - C 中 struct 类型变量的别名

c++ - 变量作为全局范围内的结构 - 如何定义?

java - 对于 public static int 我必须返回什么?

c - C中结构的动态分配

c - 如何杀死后台 worker ,包括 Postgres 中的元数据?

将帧从相机 (/dev/video0) 复制到帧缓冲区 (/dev/fb0) 会产生意外结果

c - fopen 不能同时处理超过 60 个文件

java - 使用 apache poi 循环数组数据