c++ union内存

看一个例子:

#include <iostream>
#include <stdio.h>
using namespace std;

union A {
    int a;
    struct {
        short b;
        short c;
    };
};

int main()
{
    A s;
    s.a = 0x12345678;

    printf("%x %x", s.b, s.c);
    return 0;
}

输出结果:

5678 1234

为什么是这样的呢?

因为A是union,所以在内存中存储的格式为:

高地址         ------------>    低地址

12     34    56    78

00010010 00110100   01010110   01111000

s.b 占据低地址的两个字节

s.c 占据高地址的两个字节

所以:

s.b = 5678

s.c = 1234

为了证明,以及看的更清楚,看下面这个程序。

#include <iostream>
#include <stdio.h>
using namespace std;

union A {
    int a;
    struct {
        short b;
        short c;
    };
};

int main()
{
    A s;
    s.a = 0x12345678;
    printf("b = %x ; c = %x
", s.b, s.c);
    printf("&a = %x ; &b = %x; &c = %x
", &s.a, &s.b, &s.c);
    return 0;
}

结果:

b = 5678 ; c = 1234
&a = 28ff1c ; &b = 28ff1c; &c = 28ff1e

是不是很明显了。

原文地址:https://www.cnblogs.com/chenhuan001/p/7516345.html