union type
{
long l;
char c[4];
};
union type x;
void main()
{
x.l=0x04030201;
for (int i=0;i<4;i++)
printf("c[%d] =%g\t",i,x.c[i]);
}
结果是:c[0]=1 c[1]=2 c[2]=3 c[3]=4
原因是?
如将 char c[4]改 int c[4] 结果为c[0]=1027 c[1]=513 c[2]=0 c[3]=0
这又是为什么?
/*---------------------------------------------------------------------------
File name: union-2.c
Author: HJin (email: fish_sea_bird [at] yahoo [dot] com )
Created on: 8/21/2007 05:53:14
Environment: Windows XP Professional SP2 English +
Visual Studio 2005 v8.0.50727.762
Modification history:
===========================================================================
Assume that sizes of both int and long are 4 bytes, which
is true for my VS 2005. Then sizeof type2 should be 16 bytes
on a 32-bit os.
The long "l" part shares the same memory location with c[0] on
a little endian system such as a PC with a Intel processor.
(It may share with c[3] instead if the system is big endian such
as a Motorola processor (old Mac)).
c[1], c[2], c[3] contains garbage since you did not intialize it.
output from my machine:
c[0] =1 c[1] =2 c[2] =3 c[3] =4
c[0] =67305985 c[1] =0 c[2] =0 c[3] =0 Press any key to continue . . .
*/
#include<stdio.h>
union type1
{
long l;
char c[4];
};
union type1 x;
union type2
{
long l;
int c[4];
};
union type2 y;
int main()
{
int i;
x.l=0x04030201;
for (i=0;i<4;i++)
printf("c[%d] =%d\t",i,x.c[i]);
printf("\n");
y.l=0x04030201; // decimal value is 67305985
for (i=0;i<4;i++)
printf("c[%d] =%d\t",i,y.c[i]);
return 0;
}
-------------------------------------------------------------------------------------------------------------
最后对楼主说几句:还是老老实实看基础书去,注意看我的签名。