免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
12
最近访问板块 发新帖
楼主: zdmilan
打印 上一主题 下一主题

struct的大小? [复制链接]

论坛徽章:
0
11 [报告]
发表于 2006-08-24 11:22 |只看该作者
用这个程序测试:
#include <stdio.h>

struct test
{
unsigned short a : 4;
unsigned short b : 5;
unsigned short c : 7;
};

void test_struct()
{
        struct test tt;
        unsigned short * ptr =(unsigned short *)&tt;
        int i;
        printf("size of struct = :%d \n", sizeof(struct test));

        for(ptr[0]=1, i=0; i<8*sizeof(struct test); i++, ptr[0]<<=1)
        {               
                printf("struct = %04x,  a = %02x, b = %02x, c = %02x \n", ptr[0],tt.a,tt.b,tt.c);
                printf("low addr =:  0x%02x \n", ((unsigned char*)&tt)[0]);
                printf("high addr =: 0x%02x \n", ((unsigned char*)&tt)[1]);
        }
}

void main()
{
        test_struct();
}

结论:
结论:
1. 在struct中各个bit是依次排的,可以跨越byte
2. 在x86机器(little-endian)上,字节之间的顺序是高高低低
3. 如果bit总数超过一个unsigned short,则在分配一个unsigned short
low addr <---> high addr
high bit <---> low bit
0123456701234567 (2 bytes)
aaaabbbbbccccccc

论坛徽章:
0
12 [报告]
发表于 2006-08-24 12:33 |只看该作者
噢,原来是可以跨越byte的,还以为不能呢。多谢!
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP