结构体内存对齐的一点问题

2012年6月9日 | 分类: 日志 | 标签:

结构体对齐规则如下:
数据成员最终的存放地址:对齐在自身类型长度和pragma pack(value)指定值中较小的值上。
结构体的总长度:对齐在成员类型长度最大的值和pragma pack(value)指定值中较小的值上。

#include 

typedef struct 
{
	char c;
}test_struct_a;

typedef struct 
{
	char c;
	int i[0];
}test_struct_b;

typedef struct 
{
	char c;
	short s;
}test_struct_c;

typedef struct 
{
	char c;
	int i[0]; //不占用空间,但是对于后面成员对齐有影响,对于结构体成员类型长度最大的值也起作用
	short s;
}test_struct_d;

int main()
{
	printf("sizeof test_struct_a: %d\n", sizeof(test_struct_a));//1
	printf("sizeof test_struct_b: %d\n", sizeof(test_struct_b));//4
	printf("sizeof test_struct_c: %d\n", sizeof(test_struct_c));//4
	printf("sizeof test_struct_d: %d\n", sizeof(test_struct_d));//8
	return 0;
}
目前还没有任何评论.

[cusFace:84] [cusFace:83] [cusFace:82] [cusFace:79] [cusFace:67] [cusFace:66] [cusFace:65] [cusFace:54] [cusFace:53] [cusFace:52] [cusFace:51] [cusFace:50] [cusFace:49] [cusFace:48] [cusFace:47] [cusFace:44] [cusFace:43] [cusFace:42] [cusFace:41] [cusFace:40] [cusFace:39] [cusFace:38] [cusFace:37] [cusFace:36] [cusFace:35] [cusFace:34] [cusFace:33] [cusFace:32] [cusFace:31] [cusFace:30] [cusFace:29] [cusFace:28] [cusFace:27] [cusFace:26] [cusFace:25] [cusFace:24] [cusFace:23] [cusFace:22] [cusFace:21] [cusFace:20] [cusFace:19] [cusFace:18] [cusFace:17] [cusFace:16] [cusFace:15] [cusFace:14] [cusFace:13] [cusFace:12] [cusFace:11] [cusFace:10] [cusFace:09] [cusFace:08] [cusFace:07] [cusFace:06] [cusFace:05] [cusFace:04] [cusFace:03] [cusFace:02] [cusFace:01] [cusFace:00]