如果我们只是阅读成员,我们可以使用工会而不是结构吗?

发布于 2025-02-11 04:52:05 字数 388 浏览 1 评论 0原文

因此,我的问题是,当您不更改成员时,无法使用工会而不是结构来保存内存?我知道其他成员也会受到变更操作的影响,但是我什么都不改变,如果我只想阅读它们怎么办?例如:

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 技术交流群。

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

发布评论

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

评论(1

不必在意 2025-02-18 04:52:05

my_union的原因只有4个字节是因为它仅存储一个int价值的数据。 IE my_union.age存储在与my_union.salarymy_union.id.id的同一内存位置。

因此,请这样想:“我们不能通过用单个int替换my_struct来保存8个字节?”如果答案是否定的,请考虑原因。因为这基本上是您正在做的,如果您尝试用my_union替换它。

为了帮助您可视化这一点,让我们看一下如何布置内存的my_struct vs`my_union:

my_struct

| age     | salary  | id      |
| 4 bytes | 4 bytes | 4 bytes |

ie,我们有12个字节,分为4个章节,分为4个字节每个,每个成员一个。

my_union

| age     |
| salary  | 
| id      |
| 4 bytes |

即,我们只有4个字节。我们仍然有3个成员,但它们都存储在同一位置。就像我们只有一个int

The reason that my_union is only 4 bytes is because it's only storing one int worth of data. i.e. my_union.age is stored in the same memory location as my_union.salary and my_union.id.

So, think of it like this: "Can't we save 8 bytes by replacing my_struct with a single int?" If the answer is no, think about why. Because this is basically what you're doing if you try to replace it with my_union.

To help visualize this, let's look at how the memory is laid out for my_struct vs `my_union:

my_struct:

| age     | salary  | id      |
| 4 bytes | 4 bytes | 4 bytes |

i.e., we have 12 bytes, divided into three sections of 4 bytes each, one for each member.

my_union:

| age     |
| salary  | 
| id      |
| 4 bytes |

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.

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