C语言union中包含struct 小结

#include
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
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
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语言总结)