阅读背景:

结构体内存对齐——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;
}
#include <stdio.h>
#include <string.h>
#incl



你的当前访问异常,请进行认证后继续阅读剩余内容。

分享到: