1. 程式人生 > >結構體對齊——結構體記憶體佈局

結構體對齊——結構體記憶體佈局

在C語言中,可以通過#pragma pack(n)來指定結構體按n位元組對齊(這裡的n是2的較小整數次冪)。如果程式設計者不指定對齊位元組數,那麼預設的會按照結構體中最長那一項對齊,如在64位作業系統中,當結構體中出現(void *),(long)型別,則必然是按照8位元組對齊;當最大的是int,那麼就按照4位元組對齊;對於陣列,如結構體中有int陣列int a[20],也是4位元組對齊的,只跟資料型別有關。
---------------------
作者:hust_wusen
來源:CSDN
原文:https://blog.csdn.net/hust_wusen/article/details/9492031
版權宣告:本文為博主原創文章,轉載請附上博文連結!

#include<stdio.h>
#include<stdlib.h>
//#pragma pack(2)//註釋掉這一行,按照預設的對齊方式

struct test
{
int n1;
long p;
char ch;
int n2;
char c1;
};

void print(struct test *p)
{
printf("&p->n1 : %p\n",&p->n1);
printf("&p->p : %p\n",&p->p);
printf("&p->ch : %p\n",&p->ch);
printf("&p->n2 : %p\n",&p->n2);
printf("&p->c1 : %p\n",&p->c1);
}
int main()
{
struct test t;
struct test *p = &t;
printf("sizeof(test) = %d\n",sizeof(struct test));//輸出結構體大小
printf("In stack:\n");//看在棧上的地址
print(p);
p = (struct test *)malloc(sizeof(struct test));
printf("In heap:\n");//看在堆上面的地址
print(p);
free(p);
return 1;
}

 

可以看出,由於long型別p的存在,資料結構按照8位元組對齊,其中白色部分為未使用部分,如果調整一下資料結構存放的位置,如把c1放在ch後面,那麼可以節約8位元組的空間。