结构体变量所占内存空间大小是各个成员所占内存空间大小之和,共用体变量所占内存空间大小等于成员中所占空间最大的值。
#include
using namespace std;
#pragma pack(1)//算定义内存对齐方式
struct my_struct{
char pos[20];
int grade;
};
union my_union{
char pos[20];
int grade;
};
void main (void)
{
union my_union person1;
person1.grade=22;
cout<<person1.pos<<endl;
cout<<person1.grade<<endl;
strcpy(person1.pos,"teachar");
cout<<person1.pos<<endl;
cout<<person1.grade<<endl;
union my_union person2;
person2.grade=48;
cout<<person2.pos<<endl;
cout<<person2.grade<<endl;
cout<<person1.pos<<endl;
cout<<person1.grade<<endl;
my_struct A_struct;
my_union B_union;
cout<<"my_struct A_struct:\t"<<sizeof(A_struct)<<endl;
cout<<"my_union B_union:\t"<<sizeof(B_union)<<endl;;
}