关于联合和内存管理的问题

发布于 2024-12-06 04:11:14 字数 210 浏览 2 评论 0原文

我对联合以及它们如何分配内存感到困惑。假设我有:

union Values
{
    int ivalue;
    double dvalue;
};

Values v;

所以我知道 int 使用 4 个字节,double 使用 8 个字节,所以总共分配了 8 个字节(我认为),那么 v 将使用多少内存?

I'm confused about unions and how they allocate memory. Say I have:

union Values
{
    int ivalue;
    double dvalue;
};

Values v;

So I know the int uses 4 bytes and the double uses 8 bytes, so there are 8 bytes allocated in total (I think), with that said how much memory would v use?

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

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

发布评论

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

评论(2

与往事干杯 2024-12-13 04:11:14

你几乎已经回答了你自己的问题:给定一个四字节的int和一个8字节的double,v将使用8个字节记忆。

如果不确定,您可以编译并运行一个简单的程序来打印 sizeof(v)

You've pretty much answered your own question: given a four-byte int and an 8-byte double, v would use 8 bytes of memory.

If unsure, you could compile and run a simple program that'll print out sizeof(v).

兰花执着 2024-12-13 04:11:14

鉴于 int 为 4 个字节,double 为 8 个字节(语言无法保证),sizeof (Values)< /code>至少 8 个字节。

最常见的是,它正好是 8 个字节(更一般的是 sizeof (int)sizeof (double),以较大者为准),但编译器可以添加未命名的填充结构体和联合体。对于结构体,任何此类填充都可以位于任意两个成员之间,或在最后一个成员之后;对于工会来说,只能是最后了。

这种填充的目的是为了更好地对齐。例如,假设:

union u {
    char c[5];
    int i;
};

如果 int 是 4 字节并且需要 4 字节对齐,则编译器必须添加填充以使 sizeof (union u) 至少为 8 字节。

在您的特定情况下,可能没有理由添加任何填充,但您不应该假设没有任何填充。如果您需要知道联合的大小,只需使用sizeof

Given that int is 4 bytes and double is 8 bytes (which is not guaranteed by the language), sizeof (Values) is at least 8 bytes.

Most commonly it will be exactly 8 bytes (more generally, sizeof (int) or sizeof (double), whichever is larger), but compilers are permitted to add unnamed padding to structs and unions. For structs, any such padding can be between any two mebers, or after the last one; for unions, it can only be at the end.

The purpose of such padding is to allow for better alignment. For example, given:

union u {
    char c[5];
    int i;
};

if int is 4 bytes and requires 4-byte alignment, the compiler will have to add padding to make sizeof (union u) at least 8 bytes.

In your particular case, there's probably no reason to add any padding, but you shouldn't assume that there isn't any. If you need to know the size of the union, just use sizeof.

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