Chinaunix首页 | 论坛 | 博客
  • 博客访问: 241555
  • 博文数量: 88
  • 博客积分: 1429
  • 博客等级:
  • 技术积分: 523
  • 用 户 组: 普通用户
  • 注册时间: 2010-01-18 15:31
文章分类

全部博文(88)

文章存档

2017年(2)

2016年(24)

2013年(1)

2012年(24)

2011年(15)

2010年(22)

我的朋友

分类: C/C++

2011-01-08 16:04:22

//
// 研究结构体的位段
//    参考:http://blog.sina.com.cn/s/blog_5c92220a0100nc9f.html
//
//    VC的默认对齐字节数是:4字节
//
#include <stdio.h>

struct test_8Byte{
    unsigned int a: 1;   //分配1bit
    unsigned int : 0;    //自动填充到对齐边界,这里是一个字
    unsigned int b: 6;
    unsigned int : 0;
};

struct test_4Byte{
    unsigned int a: 1;
    unsigned int : 1;    //填充1bit
    unsigned int b: 6;
    unsigned int : 0;
};

struct test_16Byte{
    unsigned int a: 1;
    unsigned int : 0;
    unsigned int b: 6;
    unsigned int : 0;
    unsigned int c: 1;    //这里会自动对齐,一个字只使用了1bit
    unsigned int d;
};

void main(){
    printf("test_8Byte = %d\n", sizeof(struct test_8Byte));
    printf("test_4Byte = %d\n", sizeof(struct test_4Byte));
    printf("test_16Byte = %d\n", sizeof(struct test_16Byte));
}


[注意]
1、不能对占1bit的的变量取地址,如&t.a,错误;
2、在结构中使用char也不会出错,参考中说只能是位段的类型必须是int,unsigned int,signed int(或加上限定符);

struct test_12Byte{
    char a: 1;    //分配1bit
    char : 0;    //自动填充到对齐边界,这里是一个字
    unsigned int b: 6;
    unsigned int : 0;
    unsigned int c;
};


3、对于占1bit的变量来说,其大小只能为0和1;
4、待深入。。。

阅读(1435) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~