zoukankan      html  css  js  c++  java
  • 结构体内存对齐——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
    ", 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
    ", &(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_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
  • 相关阅读:
    css 实现div内显示两行或三行,超出部分用省略号显示
    vue组件中的样式属性:scoped,解决在父组件中无法修改子组件样式问题
    HBuilder打包app(vue项目)
    vue动态路由传值以及get传值及编程式导航
    vue路由vue-router的安装和使用
    vue组件传值之父传子
    vue生命周期钩子函数
    vue定义组件
    vue定义自定义事件方法、事件传值及事件对象
    vue中操作Dom节点的方法
  • 原文地址:https://www.cnblogs.com/CodeWorkerLiMing/p/12007443.html
Copyright © 2011-2022 走看看