请教高手一个linux下的数据存储方式问题
我正复习准备考验,前段时间做了做专业课试题的样题,又一道题真的是把我给郁闷透了。这个题是这样的:
1.Data representation,Byte ordering,Alignment
Consider the following program:
struct s {
char c;
double d;
float f;
short s;
};
union u {
unsigned char buf[24];
struct s a;
int i;
} u1;
int main()
{
int i,j;
memset(&u1.a, 0, sizeof(struct s));
u1.a.c = 0xac;
u1.a.d = -3.3;
u1.a.f = 0x1;
u1.a.s = 0xbcde;
u1.i = 0x12345678;
/* print out the bytes of u1.buf as 2 digit hexidecimal numbers with a line break after every 8 bytes */
for(i = 0; i < 3; i++)
{
for(j = 0; j < 8; j++)
printf("0x\%.2x ",u1.buf[i*8+j]);
printf("\n");
}
}
This program is compiled and run on a Linux/x86 machine. Fill in the output below. Write “??” if the value cannot be determined from the information provided.
0x____ 0x____ 0x____ 0x____ 0x____ 0x____ 0x____ 0x____
0x____ 0x____ 0x____ 0x____ 0x____ 0x____ 0x____ 0x____
0x____ 0x____ 0x____ 0x____ 0x____ 0x____ 0x____ 0x____
Answer:
0x78 0x56 0x34 0x12 0x66 0x66 0x66 0x66
0x66 0x66 0x0a 0xc0 0x00 0x00 0x80 0x3f
0xde 0xbc 0x00 0x00 0x00 0x00 0x00 0x00
这个是复旦大学软件学院的《计算机系统基础》这门课的样题中的第一题,这个题害得我在图书馆查了一星期的资料,但最终还是没能搞定,实在没辙了。
我不明白的地方就是试题的答案。union u1 中的int型变量i实在a之后定义的,为什么会被先打印出来?而且其他的变量打印出来的顺序好像都没有按照程序中定义的顺序,这到底是怎么回事啊?望高手赐教,不胜感激。
问题点数:20、回复次数:1Top
1 楼sourceid()回复于 2006-11-05 20:34:26 得分 0
没有写入u1.i = 0x12345678之前,其中u1.a.c, u1.a.s是四字节对齐.(编译器做)
0xac 0x00 0x00 0x00
0x66 0x66 0x66 0x66 0x66 0x66 0x0a 0xc0
0x00 0x00 0x80 0x3f
0xde 0xbc 0x00 0x00
0x00 0x00 0x00 0x00
写入后,
0x78 0x56 0x34 0x12
0x66 0x66 0x66 0x66 0x66 0x66 0x0a 0xc0
0x00 0x00 0x80 0x3f
0xde 0xbc 0x00 0x00
0x00 0x00 0x00 0x00
Top




