结构体内存对齐——2
#include <stdio.h>
#include <string.h>
#include <malloc.h>
/* So, when you are working with image headers, binary headers, and network packets, and are trying to access the
TCP/ IP header, structure padding has to be avoided. */
int main(int argc, char* argv[])
{
//#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)));
对齐到4字节 = 3+3+2+4+1+1+1+1 = 16
struct gif_hdr v1 = {1,2,3,4,5,6,7,8,9,10,11};
struct gif_hdr *dsptr;
printf("Size of structure data = %d\n", sizeof(struct gif_hdr));
dsptr = (struct gif_hdr*)malloc(sizeof(struct gif_hdr));
printf("&(dsptr->signature[0]) = %p\n", &(dsptr->signature[0]));
printf("&(dsptr->version[0]) = %p\n", &(dsptr->version[0]));
printf("&(dsptr->width) = %p\n", &(dsptr->width));
printf("&(dsptr->height) = %p\n", &(dsptr->height));
printf("&(dsptr->colormap) = %p\n", &(dsptr->colormap));
printf("&(dsptr->bgcolor) = %p\n", &(dsptr->bgcolor));
printf("&(dsptr->ratio) = %p\n\n", &(dsptr->ratio));
printf("Offset of signature = %d\n", &(dsptr->signature[0]) - &(dsptr->signature[0]) );
printf("Offset of version = %d\n", &(dsptr->version[0]) - &(dsptr->signature[0]) );
printf("Offset of width = %d\n", (char*)&(dsptr->width) - &(dsptr->signature[0]));
printf("Offset of height = %d\n", &(dsptr->height) - &(dsptr->signature[0]));
printf("Offset of colormap = %d\n", &(dsptr->colormap) - &(dsptr->signature[0]));
printf("Offset of bgcolor = %d\n",&(dsptr->bgcolor) - &(dsptr->signature[0]));
printf("Offset of ratio = %d\n", &(dsptr->ratio) - &(dsptr->signature[0]));
return 0;
}
# struct_packed4.exe
Size of structure data = 16
&(dsptr->signature[0]) = 006E1898
&(dsptr->version[0]) = 006E189B
&(dsptr->width) = 006E18A0
&(dsptr->height) = 006E18A4
&(dsptr->colormap) = 006E18A5
&(dsptr->bgcolor) = 006E18A6
&(dsptr->ratio) = 006E18A7
Offset of signature = 0
Offset of version = 3
Offset of width = 8
Offset of height = 12
Offset of colormap = 13
Offset of bgcolor = 14
Offset of ratio = 15
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】博客园携手 AI 驱动开发工具商 Chat2DB 推出联合终身会员
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· ASP.NET Core - 日志记录系统(二)
· .NET 依赖注入中的 Captive Dependency
· .NET Core 对象分配(Alloc)底层原理浅谈
· 聊一聊 C#异步 任务延续的三种底层玩法
· 敏捷开发:如何高效开每日站会
· 互联网不景气了那就玩玩嵌入式吧,用纯.NET开发并制作一个智能桌面机器人(一):从.NET IoT入
· .NET 开发的分流抢票软件,不做广告、不收集隐私
· ASP.NET Core - 日志记录系统(二)
· 实现windows下简单的自动化窗口管理
· 一个超经典 WinForm,WPF 卡死问题的终极反思