一
#include<stdio.h>
int main()
{
union
{
int i;
struct
{
int j;
int m;
}byte;
struct
{
char k;
char p;
char q;
char s;
}bit;
}jin;
jin.bit.p=0x2;
jin.i=0x12345678;
printf("%x\n",jin.bit.k);
printf("%x\n",jin.bit.p);
printf("%x\n",jin.bit.q);
printf("%x\n",jin.bit.s);
printf("%d\n",sizeof(jin));
}
编译:
[root@localhost algorithm]# gcc jin.c -o jin
^[[A[root@localhost algorithm]# ./jin
78
56
34
12
8
证明了我的编译器是小端模式。
二
#include<stdio.h>
int main()
{
union
{
int i;
struct
{
int j;
int m;
}byte;
struct
{
char k;
char p;
char q;
char s;
}bit;
}jin;
jin.i=0x12345678; //与一互换
jin.bit.p=0x2;
printf("%x\n",jin.bit.k);
printf("%x\n",jin.bit.p);
printf("%x\n",jin.bit.q);
printf("%x\n",jin.bit.s);
printf("%d\n",sizeof(jin));
}
编译:
[root@localhost algorithm]# gcc jin.c -o jin
^[[A[root@localhost algorithm]# ./jin
78
2
34
12
8
与一相比,56变成了2.
三
#include<stdio.h>
int main()
{
union
{
int i;
struct
{
int j;
int m;
}byte;
struct
{
char k;
char p;
char q;
char s;
}bit;
}jin;
jin.bit.p=0x2;
jin.i=0x12345678;
printf("%x\n",jin.bit.k);
printf("%x\n",jin.bit.p);
printf("%x\n",jin.bit.q);
printf("%x\n",jin.bit.s);
printf("%x\n",jin.byte.j);
printf("%d\n",sizeof(jin));
// printf("%x\n",jin.byte.j);
}
多了一行黑体。
编译:
[root@localhost algorithm]# vim jin.c
[root@localhost algorithm]# gcc jin.c -o jin
^[[A[root@localhost algorithm]# ./jin
78
56
34
12
12345678
8
打印多了12345678这一行。
若把黑体printf("%x\n",jin.byte.j);改为printf("%x\n",jin.byte.m);则打印的是随意的数字,因为没初始化m,空间只初始化一个int。
本文通过三个实例展示了C语言中union如何与包含struct的交互,探讨了小端模式下数据存储的特性。通过设置并打印union中的不同成员,观察到数据在内存中的表示和变化,揭示了内存对齐和数据类型转换的原理。
3万+

被折叠的 条评论
为什么被折叠?



