灵活的数组成员会增加结构的大小吗? [英] Does a flexible array member increase sizeof a struct?

查看:35
本文介绍了灵活的数组成员会增加结构的大小吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下类型的代码:

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 成员的信息?

Problematic line is the line with sizeofs. I am not sure is that correct way to count needed space. Does sizeof(*msg) contains already something about the list member?

我可以用我的编译器测试它,但在这种情况下每个编译器的工作方式都相似吗?

I can test it with my compiler, but does every compiler work similary in this case?

推荐答案

这是标准所说的:

作为一种特殊情况,结构的最后一个元素具有多个命名成员可能具有不完整的数组类型;这被称为灵活的数组成员.在大多数情况下,灵活的数组成员被忽略.尤其是,结构的大小就好像灵活的数组成员被省略,只是它可能有更多比省略所暗示的尾随填充.

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.

这篇关于灵活的数组成员会增加结构的大小吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆