前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >结构体内存对齐——2

结构体内存对齐——2

作者头像
用户4645519
发布2020-09-07 11:07:39
3920
发布2020-09-07 11:07:39
举报
文章被收录于专栏:嵌入式学习嵌入式学习
代码语言:javascript
复制
#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;
}
代码语言:javascript
复制
# 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
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018-09-07 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档