#include <iostream.h> #include <iomanip.h> union Num { char a[4]; int b; }; void main() { Num x; x.a[0]=‘A’; x.a[1]=‘B’; x.a[2]=‘C’; x.a[3]=‘D’; cout<<x.a<<endl; cout<<x.b<<endl; cout<<hex<<x.b<<endl; }
输出结果: ABCD?<>捡 1145258561 44434241
(1)连结体 x在像LZ这样的程序赋值之后,在小端机 内从的存储状况(16进制)如下:
41 42 43 44,在输出x.b即将这四个字节以整数输出,由于是小段存储,则其对应的整数是0x 44434241,其
对应的十进制为1145258561
(2)当输出数组时,是将数组名所指向的地址逐个字符输出,知道遇到'\0',x.a是一个字符数组,但是C风格
字符串,C风格字符串是以‘\0’结尾的字符串,所以输出x.a时会出现乱码。
(3)如果LZ这样修改代码,则输出正常
#include <iostream.h> #include <iomanip.h> union Num { char a[4]; int b; }; void main() { Num x; x.a[0]='A'; x.a[1]='B'; x.a[2]='C'; x.a[3]='D'; x.a[4]='\0';//利用数组越界,但是比较危险 cout<<x.a<<endl; cout<<x.b<<endl; cout<<hex<<x.b<<endl; }