• 结构体内存对齐_1


    #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;
            int height;
            char colormap;
            char bgcolor;
            char ratio;
        }__attribute__((__packed__));
    	不对齐,结构体的长度,就是各个变量长度的和 = 3+3+2+4+4+1+1+1 = 19
    	
        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
    ", sizeof(struct gif_hdr));
        dsptr = (struct gif_hdr*)malloc(sizeof(struct gif_hdr));
    	
    	printf("&(dsptr->signature[0]) = %p
    ", &(dsptr->signature[0]));
    	printf("&(dsptr->version[0]) = %p
    ", &(dsptr->version[0]));
    	printf("&(dsptr->width) = %p
    ", &(dsptr->width));
    	printf("&(dsptr->height) = %p
    ", &(dsptr->height));
    	printf("&(dsptr->colormap) = %p
    ", &(dsptr->colormap));
    	printf("&(dsptr->bgcolor) = %p
    ", &(dsptr->bgcolor));
    	printf("&(dsptr->ratio) = %p
    
    ", &(dsptr->ratio));
    	
        printf("Offset of signature = %d
    ", &(dsptr->signature[0]) - &(dsptr->signature[0]) );
        printf("Offset of version = %d
    ", &(dsptr->version[0]) - &(dsptr->signature[0]) );
        printf("Offset of width = %d
    ", (char*)&(dsptr->width) - &(dsptr->signature[0]));
        printf("Offset of height = %d
    ", (char*)&(dsptr->height) - &(dsptr->signature[0]));
        printf("Offset of colormap = %d
    ", &(dsptr->colormap) - &(dsptr->signature[0]));
        printf("Offset of bgcolor = %d
    ",&(dsptr->bgcolor) - &(dsptr->signature[0]));
        printf("Offset of ratio = %d
    ", &(dsptr->ratio) - &(dsptr->signature[0]));
        return 0;
    }
    
    # struct_packed2.exe
    Size of structure data = 19
    &(dsptr->signature[0]) = 008C1898
    &(dsptr->version[0]) = 008C189B
    &(dsptr->width) = 008C18A0
    &(dsptr->height) = 008C18A4
    &(dsptr->colormap) = 008C18A8
    &(dsptr->bgcolor) = 008C18A9
    &(dsptr->ratio) = 008C18AA
    
    Offset of signature = 0
    Offset of version = 3
    Offset of width = 8
    Offset of height = 12
    Offset of colormap = 16
    Offset of bgcolor = 17
    Offset of ratio = 18
  • 相关阅读:
    PhpStorm 常用快捷键和配置+关闭快捷键ctrl+alt+方向键旋转屏幕+快速复制一行快捷键恢复
    WP七牛云插件详解
    注册表删除键值时拒绝访问
    删除注册表子项清除u盘使用痕迹
    一件代发发货人怎么写?淘宝代理发货流程
    联动设置
    使用vue实现行列转换的一种方法。
    从后端到前端之Vue(五)小试路由
    从后端到前端之Vue(四)小试牛刀——真实项目的应用(树、tab、数据列表和分页)
    从后端到前端之Vue(三)小结以及一颗真实的大树
  • 原文地址:https://www.cnblogs.com/CodeWorkerLiMing/p/12007444.html
Copyright © 2020-2023  润新知