灵活的数组成员会增加结构的大小吗?
我有以下类型的代码:
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
标准是这样说的:
Here's what the standard says:
你的例子确实有效,因为 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.