结构体内存对齐

#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[])
{
    struct gif_hdr
    {
        char signature[3];
        char version[3];
        int width;
        int height;
        char colormap;
        char bgcolor;
        char ratio;
    };
3+3+2+4+4+1+1+1+1 = 20
	
    struct gif_hdr v1;
    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.exe
Size of structure data = 20
&(dsptr->signature[0]) = 00491878
&(dsptr->version[0]) = 0049187B
&(dsptr->width) = 00491880
&(dsptr->height) = 00491884
&(dsptr->colormap) = 00491888
&(dsptr->bgcolor) = 00491889
&(dsptr->ratio) = 0049188A

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
原文地址:https://www.cnblogs.com/CodeWorkerLiMing/p/12007445.html