结构体内存对齐_1

时间:2022-07-24
本文章向大家介绍结构体内存对齐_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 = %dn", sizeof(struct gif_hdr));
    dsptr = (struct gif_hdr*)malloc(sizeof(struct gif_hdr));
	
	printf("&(dsptr->signature[0]) = %pn", &(dsptr->signature[0]));
	printf("&(dsptr->version[0]) = %pn", &(dsptr->version[0]));
	printf("&(dsptr->width) = %pn", &(dsptr->width));
	printf("&(dsptr->height) = %pn", &(dsptr->height));
	printf("&(dsptr->colormap) = %pn", &(dsptr->colormap));
	printf("&(dsptr->bgcolor) = %pn", &(dsptr->bgcolor));
	printf("&(dsptr->ratio) = %pnn", &(dsptr->ratio));
	
    printf("Offset of signature = %dn", &(dsptr->signature[0]) - &(dsptr->signature[0]) );
    printf("Offset of version = %dn", &(dsptr->version[0]) - &(dsptr->signature[0]) );
    printf("Offset of width = %dn", (char*)&(dsptr->width) - &(dsptr->signature[0]));
    printf("Offset of height = %dn", (char*)&(dsptr->height) - &(dsptr->signature[0]));
    printf("Offset of colormap = %dn", &(dsptr->colormap) - &(dsptr->signature[0]));
    printf("Offset of bgcolor = %dn",&(dsptr->bgcolor) - &(dsptr->signature[0]));
    printf("Offset of ratio = %dn", &(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