C语⾔union中包含struct⼩结⼀
#include<stdio.h>
int main()
{
union
{
int i;
struct
{
int j;
int m;
}byte;
struct
{
char k;
c语言struct头文件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
证明了我的编译器是⼩端模式。
⼆
{
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.
三
{
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。
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论