加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 03:28:17 所属栏目:百科 来源:网络整理
导读:我有以下类型的代码: 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(
我有以下类型的代码:
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)是否包含有关列表成员的内容?

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

解决方法

这是标准所说的:

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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读