我有以下类型的代码:
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/