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

发布于 2024-11-24 10:27:00 字数 483 浏览 2 评论 0原文

我有以下类型的代码:

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

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

I have the following kind of code:

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 ); 

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

鲸落 2024-12-01 10:27:00

标准是这样说的:

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

Here's what the standard says:

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 没有在添加元素时动态变大的数组。因此 *msg 的大小是 sizeof u32 + paddings(如果有),但它不会计入列表成员,当您“分配”缓冲区以及当您想知道该“的实际大小”时,您必须自己考虑这一点对象”,就像你所做的那样。

Your example do work since C has not arrays that dynamically become bigger when you add elements. So size of *msg is sizeof u32 + paddings, if any, but it won't count for list member, which you have to consider by yourself when you "alloc" the buffer and when you want to know the actual size of that "object", as you did.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文