1. 有一个结构体如下
-
#include <stdio.h>
-
#include <stdlib.h>
-
#pragma pack (4)
-
-
typedef struct _STRU_TEST
-
{
-
unsigned int unLen;
-
unsigned char ucHeader;
-
unsigned char ucType;
-
unsigned short usAddr;
-
}STRU_TEST;
-
-
void main(void)
-
{
-
STRU_TEST t1;
-
int temp = sizeof(t1);
-
printf("temp = %d\n",temp);
-
return ;
-
}
2. 修改一下
-
typedef struct _STRU_TEST
-
{
-
unsigned int unLen;
-
unsigned char ucHeader;
-
unsigned short usAddr;
-
unsigned char ucType;
-
}STRU_TEST;
打印出temp=12.
3. 只是调了一下顺序,为什么会出现这么大的差别呢?
两个规则:
a. 结构体内部: 编译器为结构的每个成员按其自然对界与#pragma pack指定值中较小的那个进行对齐。
b. 结构体整体: 按照结构体中最大的数据成员和#pragma pack指定值中较小的那个进行对齐。
-
typedef struct _STRU_TEST
-
{
-
unsigned int unLen; [0-3]
-
unsigned char ucHeader; [4]
-
unsigned char ucType; [5]
-
unsigned short usAddr; [6-7]
-
}STRU_TEST1;
-
typedef struct _STRU_TEST
-
{
-
unsigned int unLen; [0-3]
-
unsigned char ucHeader; [4]
-
unsigned short usAddr; [6-7] //按照规则a,short类型自身长度为2, pragma为4,按照2字节对齐,所以这儿不是[5-6]而是[6-7]
-
unsigned char ucType; [8]
-
}STRU_TEST2;
结构体STRU_TEST2实际占的内存空间为9个字节,但是结构体的对齐是按照规则b: 结构体最大数据成员int 为4字节,pragma中指定4,所以整个结构体按4字节对齐,所以sizeof=12.
4. linux 下指定对齐
gcc 有关键字 __attribute__来指定对齐
-
#include <stdio.h>
-
#include <stdlib.h>
-
#pragma pack (4)
-
-
typedef struct _STRU_TEST
-
{
-
unsigned int unLen;
-
unsigned char ucHeader;
-
unsigned short usAddr;
-
unsigned char ucType;
-
//}STRU_TEST;
-
}__attribute__ ((packed, aligned(1)))STRU_TEST ;
-
-
void main(void)
-
{
-
STRU_TEST t1;
-
int temp = sizeof(t1);
-
printf("temp = %d\n",temp);
-
return ;
-
}
最后打印 temp=8; int 4+ char 1+ short 2+ char 1 = 8
阅读(1737) | 评论(0) | 转发(0) |