博客
关于我
结构体内存对齐——2
阅读量:581 次
发布时间:2019-03-11

本文共 929 字,大约阅读时间需要 3 分钟。

重新优化后的内容:

在实际开发中,我们需要了解如何正确地对齐和解析各种数据格式。以下是一个关于GIF头片结构对齐方式的实际示例:

#pragma pack(1)  struct gif_hdr  {      char signature[3];      char version[3];      int width;      char height;      char colormap;      char bgcolor;      char ratio;  } __attribute__((aligned(4)));  // 结构体大小计算  struct gif_hdr v1 = {1,2,3,4,5,6,7,8,9,10,11};  struct gif_hdr *dsptr;  // 分配结构体内存  dsptr = (struct gif_hdr *)malloc(sizeof(struct gif_hdr));  // 打印结构体地址和偏移量  printf("结构体地址:%p\n", dsptr);  printf("结构体大小:%d\n", sizeof(struct gif_hdr));  // 打印各字段的偏移量  printf("字段名:地址Offset\n");  printf("signature[0]:%p\n", dsptr->signature[0]);  printf("version[0]:%p\n", dsptr->version[0]);  printf("width:%p Offset\n", (char *)dsptr->width, dsptr->signature[0]);

输出结果:

结构体地址:006E1898

结构体大小:16
signature[0]:006E1898 Offset
version[0]:006E189B Offset
width:006E18A0 Offset
height:006E18A4 Offset
colormap:006E18A5 Offset
bgcolor:006E18A6 Offset
ratio:006E18A7 Offset

转载地址:http://qjrvz.baihongyu.com/

你可能感兴趣的文章
PAT (Basic Level) Practice 乙级1051-1055
查看>>
PAT (Basic Level) Practise - 写出这个数
查看>>
PAT 1027 Colors in Mars
查看>>
PAT 1127 ZigZagging on a Tree[难]
查看>>
PAT 2-07. 素因子分解(20)
查看>>
SparkSQL学习03-数据读取与存储
查看>>
PAT L2-012. 关于堆的判断
查看>>
PAT Spell It Right [非常简单]
查看>>
PAT-1044. Shopping in Mars (25)
查看>>
PAT-乙级-1040 有几个PAT
查看>>
PAT1093 Count PAT's (25)(逻辑题)
查看>>
PATA1038题解(需复习)
查看>>
Patching Array
查看>>
Spring源码学习(二):Spring容器之prepareContext和BeanFactoryPostProcessor的介绍
查看>>
PatchMatchStereo可能会需要的Rectification
查看>>
Path does not chain with any of the trust anchors
查看>>
Path形状获取字符串型变量数据
查看>>
PAT甲级——1001 A+B Format (20分)
查看>>
Skywalking原理
查看>>
PAT甲级——1006 Sign In and Sign Out (25分)
查看>>