结构体的默认存储方式采用以最大字节元素字节数对其方式进行对齐,例如一个结构体中定义有char、int类型元素,则结构体存储空间按照int类型占用字节,如果还有double类型元素,则结构体存储空间按double类型占用字节对其。针对该特性特意编写如下测试代码:
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int main(int argc, char *argv[]) {
int i = 0;
printf("struct test...\r\n");
struct _s
{
unsigned char elem; unsigned int elem1; /*int 存储空间为4字节*/ }s = {3, 4}; struct _t { unsigned char elem; unsigned int elem2; double elem1; /*double 存储空间为8字节*/ }t = {8, 9, 9.9}; struct _y { unsigned char elem; double elem1; /*double 存储空间为8字节*/ unsigned int elem2; }y; printf("int char = %d\r\n", sizeof(int)/sizeof(char)); printf("float char = %d\r\n", sizeof(float)/sizeof(char)); printf("double char = %d\r\n", sizeof(double)/sizeof(char)); printf("struct _y char count = %d\r\n", sizeof(struct _y)/sizeof(char)); /* 默认输出 */ printf("struct _s char count = %d\r\n", sizeof(struct _s)/sizeof(char)); for( i=0; i< sizeof(struct _s)/sizeof(char); ++i) printf("index %d = %d, ", i, *((unsigned char*)(&s)+i)); printf("struct _t char count = %d\r\n", sizeof(struct _t)/sizeof(char)); for( i=0; i< sizeof(struct _t)/sizeof(char); ++i) printf("index %d = %d, ", i, *((unsigned char*)(&t)+i)); /* 将struct _s的存储空间所有字节赋值为0 */ for( i=0; i< sizeof(struct _s)/sizeof(char); ++i) *((unsigned char*)(&s)+i) = 0; s.elem = 2; s.elem1 = 5; for( i=0; i< sizeof(struct _t)/sizeof(char); ++i) *((unsigned char*)(&t)+i) = 0; t.elem = 8; t.elem2 = 9.9; t.elem1 = 6; printf("\r\nstruct _s char count = %d\r\n", sizeof(struct _s)/sizeof(char)); for( i=0; i< sizeof(struct _s)/sizeof(char); ++i) printf("index %d = %d, ", i, *((unsigned char*)(&s)+i)); printf("\r\nstruct _t char count = %d\r\n", sizeof(struct _t)/sizeof(char)); for( i=0; i< sizeof(struct _t)/sizeof(char); ++i) printf("index %d = %d, ", i, *((unsigned char*)(&t)+i)); return 0; }
编译运行上述代码,结构体_s, _t, _y的存储空间分别为8,16,24。对比可知结构体存储空间大小能被结构体空间最大元素占用字节数整除,并且如果相邻元素空间大小累加小于单位最大空间大小,会尝试再次累加,累加如果大于最大空间大小,则选择扩充之前元素的空间大小。