码迷,mamicode.com
首页 > 其他好文 > 详细

Union大小

时间:2014-09-28 21:10:05      阅读:171      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   io   ar   sp   div   on   c   

在一个union类型结构中,所有的成员公用同样的存储空间,其占用的大小为其成员中需要空间最大者;

union本身只保留一块地址空间,因为只有一个成员真正存储于该地址, 但这块地址也要满足内存对齐原则。

 1 #include <stdio.h>
 2 
 3 union U1 {
 4     int a;
 5     char b;
 6 };
 7 
 8 union U2 {
 9     char a[9];
10     double b;
11 };
12 
13 union U3 {
14     U1 a;
15     U2 b;
16     char c[18];
17 };
18 int main() {
19     printf("size of U1: %ld\n", sizeof(U1));
20     printf("size of U2: %ld\n", sizeof(U2));
21     printf("size of U3: %ld\n", sizeof(U3));
22     return 0;
23 }

注意U3对齐还是以前面的double进行对齐,所以应该是对齐到下一个8的位数,也就是24,而不是20.

1 root@xxj-VirtualBox:~/interview# ./union 
2 size of U1: 4
3 size of U2: 12
4 size of U3: 20

 

Union大小

标签:style   blog   color   io   ar   sp   div   on   c   

原文地址:http://www.cnblogs.com/linyx/p/3998893.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!