c++ union内存

时间:2023-03-10 01:53:22
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 ;
}

输出结果:

 

为什么是这样的呢?

因为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\n", s.b, s.c);
printf("&a = %x ; &b = %x; &c = %x\n", &s.a, &s.b, &s.c);
return ;
}

结果:

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

是不是很明显了。