内存对齐初探

test.c

 

#include <stdio.h>

struct stu{
        char sex;
        int length;
        char name[10];
};

int main()
{
        char name[10];
        struct stu mystu;
        printf("size of char:%d\n", sizeof(char));
        printf("size of int: %d\n", sizeof(int));
        printf("size of char[10]:%d\n", sizeof(name));
        printf("size of stu:%d\n", sizeof(mystu));

        return 0;
}

 

 

运行结果 
[zxnms@/home/zxnms]$gcc -o test test.c
[zxnms@/home/zxnms]$./test
size of char:1
size of int: 4
size of char[10]:10
size of stu:20

主意: 这里的stu不是应该返回1+4+10 = 15吗?

 

结果分析:

gcc默认按四个字节对齐

struct stu{
        char sex;
        int length;
        char name[10];
};

sex 1个字节不足4个字节,补足4个字节

length 4个字节

name 8个字节,剩余两个字节:2 不足4个字节

总: 4 + 4 + 8 + 4 = 20

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值