共用体类型变量的内存分配问题:
一句话共用体变量的内的各个成员都是从低字节开始公用的;
比如union UnionType{
int x;
char ch[4];
}temp;
x = 24897; //x的二进位为(从高位到低位依次) 00000000 00000000 01100001 01000001
此时 ch[0] 的二进制就为 01000001 //x的低八位
ch[1] ... 01100001
ch[2] ... 00000000
ch[3] ... 00000000
对其temp成员进行输出就是 temp.x = 24897;
temp.ch[0] = 'A';
temp.ch[1] = 'a';
参考代码:
#include<iostream>
#include<bitset>
using namespace std;
int main()
{
union UnionType{
int x;
char ch[2];
} temp;
temp.x = 24897;
cout<<"temp.x = "<<temp.x<<" temp.ch[0] = "<<temp.ch[0]<<" temp.ch[1] = "<<temp.ch[1]<<endl;
bitset<32> bin(temp.x);
cout<<"temp.x(24897)的二进制数为 : "<<bin<<endl;
bin = temp.ch[0];
cout<<"temp.ch[0](A)的二进制数为 : "<<bin<<endl;
bin = temp.ch[1];
cout<<"temp.ch[1](a)的二进制数为 : "<<bin<<endl;
system("pause");
return 0;
}