如果我们只是阅读成员,我们可以使用工会而不是结构吗?
因此,我的问题是,当您不更改成员时,无法使用工会而不是结构来保存内存?我知道其他成员也会受到变更操作的影响,但是我什么都不改变,如果我只想阅读它们怎么办?例如:
struct my_struct{
int age;
int salary;
int id;
};
我们不能通过简单地用Union替换struct(如果不更改任何内容)来保存8个字节?
union my_union{
int age;
int salary;
int id;
};
sizeof(my_union)是4,而sizeof(my_struct)为12。这只是一个例子,但是如果我们不需要实际更改任何内容,我们不能这样做吗?
So, my question is, can't memory be saved by using unions instead of structs when you aren't changing the members? I know that other members will also be affected by change operations, but what I don't change anything, what if I just want to read them? For example:
struct my_struct{
int age;
int salary;
int id;
};
Can't we save 8 bytes there by simply replacing struct with union(if I don't change anything)?
union my_union{
int age;
int salary;
int id;
};
sizeof(my_union) is 4, and sizeof(my_struct) is 12. This is just an example, but can't we do this if we don't need to actually change anything?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
my_union
的原因只有4个字节是因为它仅存储一个int
价值的数据。 IEmy_union.age
存储在与my_union.salary
和my_union.id.id
的同一内存位置。因此,请这样想:“我们不能通过用单个
int
替换my_struct
来保存8个字节?”如果答案是否定的,请考虑原因。因为这基本上是您正在做的,如果您尝试用my_union
替换它。为了帮助您可视化这一点,让我们看一下如何布置内存的
my_struct
vs`my_union:my_struct
:ie,我们有12个字节,分为4个章节,分为4个字节每个,每个成员一个。
my_union
:即,我们只有4个字节。我们仍然有3个成员,但它们都存储在同一位置。就像我们只有一个
int
。The reason that
my_union
is only 4 bytes is because it's only storing oneint
worth of data. i.e.my_union.age
is stored in the same memory location asmy_union.salary
andmy_union.id
.So, think of it like this: "Can't we save 8 bytes by replacing
my_struct
with a singleint
?" If the answer is no, think about why. Because this is basically what you're doing if you try to replace it withmy_union
.To help visualize this, let's look at how the memory is laid out for
my_struct
vs `my_union:my_struct
:i.e., we have 12 bytes, divided into three sections of 4 bytes each, one for each member.
my_union
:i.e. we have only have 4 bytes. We still have 3 members, but they're all stored in the same spot. It's like we just have a single
int
.