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
这又是为什么?
----------------解决方案--------------------------------------------------------
你肯定是用TC对这段代码进行编译~~~~
----------------解决方案--------------------------------------------------------
/*---------------------------------------------------------------------------
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;
}
----------------解决方案--------------------------------------------------------
LS,E语强呀!
----------------解决方案--------------------------------------------------------
HJin把c++版的习惯带到了c版,这里人的水平可能看不懂英文,我给你翻译一下。(HJin在国外,使用的系统没有中文支持)
--------------------------------------------------------------------------------------------------------------
运行环境: Windows XP Professional SP2 English +
Visual Studio 2005 v8.0.50727.762
假设int和long都是4个字节, 至少在我的VS 2005中是这样的. 这时在一个32位操作系统中type2就是16个字节。
"l"和c[0]在一个小尾数系统[/*little endian不好翻译,有些书翻译为“小尾数”*/]如Intel处理器[/*最好改为IA-32处理器,Intel,AMD,Cyrix的处理器都是Intel-Architecture 32类型的*/]中是共享一段相同的内存位置。(在大尾数如老的MAC机用的Motorola处理器中,它就和c[3]共用内存)。c[1], c[2], c[3]在没有初始化之前保存的是内存垃圾数据。
-------------------------------------------------------------------------------------------------------------
最后对楼主说几句:还是老老实实看基础书去,注意看我的签名。
----------------解决方案--------------------------------------------------------
如果学了汇编,这问题蛮好想通的,同样是一块内存区就看你怎么解释了
----------------解决方案--------------------------------------------------------