c - 灵活的数组成员是否会增加结构的大小?

标签 c struct sizeof

我有以下类型的代码:

typedef struct
{    
    u32 count;
    u16 list[];   
} message_t;
...

message_t* msg = (message_t*)buffer;  
msg->count = 2;
msg->list[0] = 123;
msg->list[1] = 456;

size_t total_size = sizeof(*msg) + sizeof(msg->list[0]) * msg->count;  

send_msg( msg, total_size ); 

有问题的行是带有 sizeofs 的行。我不确定计算所需空间的正确方法是否正确。 sizeof(*msg) 是否已经包含关于 list 成员的信息?

我可以使用我的编译器对其进行测试,但在这种情况下每个编译器的工作方式是否相似?

最佳答案

标准是这样说的:

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 - 灵活的数组成员是否会增加结构的大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6732184/

相关文章:

c++ - 为什么在关闭初始程序后我在 ncat 上看不到 UDP?

VS2012中的C2059 : How to initialize struct instance?

C# <-> C++ : Marshaling an [In, Out] 包含 Char[] 的结构

c - 在 C 中使一个指针指向另一个指针所指向的内容

c++ - 为什么 int 在 64 位编译器上通常是 32 位?

c - GCC 没有发出警告,尽管它应该发出警告

c - 在编译时执行 C 宏函数

c - 如何找到数组的大小(从指向数组第一个元素的指针)?

c - 如何在不使用 for 循环的情况下获取 char * 变量的大小?

objective-c - 如何在 Objective-C 中编写 'global' 内联函数(使用 C 语法)