关于联合体union的内存空间
#include<iostream> using namespace std; //相同的内存地址 union myun { struct { int x; int y; int z; }u; int k; }a; int main() { a.u.x =4; a.u.y =5; a.u.z =6; a.k = 0; //覆盖掉第一个int空间值 printf("%d %d %d %d\n",a.u.x,a.u.y,a.u.z,a.k); system("pause"); return 0; }
运行程序结果为:
tonyyan@tonyyan-ThinkPad-T480s:~/Documents/CPlusPlusThings/practical_exercises/10_day_practice/day1$ ./union 0 5 6 0
#include<iostream> using namespace std; //相同的内存地址 union myun { struct { int x; int y; int z; }u; int k; int g; }a; int main() { a.u.x =4; a.u.y =5; a.u.z =6; a.k = 0; //覆盖掉第一个int空间值 a.g = 99; printf("%d %d %d %d %d\n",a.u.x,a.u.y,a.u.z,a.k,a.g); system("pause()"); return 0; }
运行结果为:
tonyyan@tonyyan-ThinkPad-T480s:~/Documents/CPlusPlusThings/practical_exercises/10_day_practice/day1$ ./union 99 5 6 99 99
实验结论:
在C/C++中,结构体struct 中的变量空间独立,联合体union的变量共享内存(最大的变量大小),union中各个变量相对于基准地址的偏移量为零。
参考:
https://github.com/Light-City/CPlusPlusThings/blob/master/practical_exercises/10_day_practice/day1/%E8%81%94%E5%90%88%E4%BD%93%E5%AD%A6%E4%B9%A0.cpp