结构体的使用与对齐

1.结构体用指针表示

#include <stdio.h>

struct s
{
        char c;
        int b;

};

int main(void)
{
        struct s s1;
        s1.c = 't';
        s1.b = 12;

        printf("len = %ld\n",sizeof(struct s));
        char *p1 = (char *)(&s1);	//将结构体用指针的方式表示
        printf("*p1 = %c\n",*p1);
        printf("s1.c = %c\n",s1.c);
        int *p2 = (int *)((long unsigned int)&s1+4);	//强制转换为int型会出现段错误

        printf("*p2 = %d\n",*p2);
		printf("s1.c = %d\n",s1.b);

        return 0;
}

2.通过使用
#pragma pack()
~~~~~~~~~~
#pragma pack()
来制定该范围内对齐规则;

对齐原则遵循最后一个变量类型必须是对齐字节数的整数倍;

 1 #include <stdio.h>
 2 
 3 #pragma pack(8)			//和第40行共同起到8字节对齐的作用
 4 
 5 
 6                         //结果为1的整数倍  结果为4的整数倍   结果为8的整数倍
 7 
 8 struct a                //一字节        四字节          八字节
 9 {
 10         char ad;        //1             4               4(1+3)
 11         int dfs;        //4             4               4
 12         double dou;     //8             8               8
 13 
 14 };
 15 
 16 struct b                //一字节        //四字节        八字节
 17 
 18 {
 19         int d;          //4             4               4
 20         char name[10];  //10            10              10
 21         short i;        //2             2               2
 22         double j;       //8             8               8
 23 };
 24 
 25 struct c                //一字节        //四字节        八字节
 26 {
 27         int wq;         //4             4               8
 28         struct b b1;    //24            24              24
 29         char oe;        //1             4               8
 30 
 31 };
 32 
 33 struct s
 34 {
 35         char c;
 36         int b;
 37 
 38 };
 39 
 40 #pragma pack()
 41 
 42 int main(void)
 43 {
 44         printf("sizeof(struct a) = %ld\n",sizeof(struct a));
 45         printf("sizeof(struct b) = %ld\n",sizeof(struct b));
 46         printf("sizeof(struct c) = %ld\n",sizeof(struct c));
 47		return 0;
 48}

3.用__attribute__((packed)):对类型进行1字节对齐
用__attribute__((aligned(n))):对类型整体进行n字节对齐

#include <stdio.h>

struct a
{
        int sf;
        char w;
        short ok;

}__attribute__((packed));

int main(void)
{
        printf("sizeof(struct a) = %ld\n",sizeof(struct a));

        return 0;
}


#include <stdio.h>

struct a
{
        char w;		 //4(1+3)
        int sf;		//4
        short ok;	//8(2+6)
        double wf;	//8

}__attribute__((aligned(8)));

int main(void)
{
        printf("sizeof(struct a) = %ld\n",sizeof(struct a));

        return 0;
}


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值