内存对齐

typedef struct
{
//这里的冒号代表的是占用的bit数
unsigned int a:1;//占用1个bit
unsigned int b:7;//占用7个bit
}T;


#include <stdio.h>
typedef struct
{
unsigned int a:1;
unsigned int b:7;
}T1;
typedef struct
{
unsigned int a:2;
unsigned int b:7;
}T2;
void main()
{
    printf("the size of struct T1 is %d\n",sizeof(T1));
    printf("the size of struct T2 is %d\n",sizeof(T2));
    getchar();
}

/*
打印结果:
    the size of struct T1 is 4
    the size of struct T2 is 4

分析:
    unsigned int 为32位四字节。 a和b总共占用了32位中的8位,剩余24位空位。
    因为存在结构体内存对齐情况,大小为32位四字节的整数倍,所以向上取最小满足字节,4位。
    
    修改如下:
        typedef struct
        {
            unsigned int a:2;
            unsigned int b:7;
            unsigned int c:7;
            unsigned int d:15;
            unsigned int e:2;
        }T2;
        sizeof(T2) == 8;    结构体内部总共字节位数为33位,本结构体使用unsigned int类型,所以字节大小应该为32位4字节的整数倍,
        因而最少取64位即8字节。
    */

    #include <stdio.h>
typedef struct
{
    unsigned int a:2;
    unsigned int b:7;
}T;
void main()
{
    T t;
    int i;
    for(;;)
    {
        printf("Please input a number:");
        scanf("%d",&i);
        t.a=i;
        printf("t.a=%d\n",t.a);
    }
}

/*
运行结果:
    Please input a number:4
    t.a=0
    Please input a number:5
    t.a=1
    Please input a number:6
    t.a=2
    Please input a number:7
    t.a=3
    Please input a number:1001
    t.a=1
    Please input a number:1546
    t.a=2
*/


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值