您的位置:首页 > 编程语言 > C语言/C++

C语言union中包含struct 小结

2012-11-20 21:32 281 查看


#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);改为[b]printf("%x\n",jin.byte.m);则打印的是随意的数字,因为没初始化m,空间只初始化一个int。

[/b]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: