sizeof(联合)值的理解
先来看各种类型在内存中所占用的空间大小
#include<stdio.h>
int main(void)
{
printf("Int sizeof:%d/n",sizeof(int));
printf("Char sizeof:%d/n",sizeof(char));
printf("Float sizeof:%d/n",sizeof(float));
printf("Double sizeof:%d/n",sizeof(double));
}
运行结果(单位是字节):
Int sizeof:4
Char sizeof:1
Float sizeof:4
Double sizeof:8
再写一个联合的例子,并打印出最终值:
#include<stdio.h>
int main(void)
{
typedef union _DATE{
char a;
int i[5];
double b;
}DATE;
DATE max;
printf("The union DATE sizeof:%d/n/n",sizeof(max));
printf("Int sizeof:%d/n",sizeof(int));
printf("Char sizeof:%d/n",sizeof(char));
printf("Float sizeof:%d/n",sizeof(float));
printf("Double sizeof:%d/n",sizeof(double));
}
运行结果:
The union DATE sizeof:24
Int sizeof:4
Char sizeof:1
Float sizeof:4
Double sizeof:8
max的值为24字节对照上面给出的类型大小不难得出结果:
Int为4,数组i有5个元素,在内存中的结构为:
char |||||
int |4 |4 |4 |4 |4 |
double| 8 |
如果没有double,按4字节对齐,但是偏偏还有一个double,按8字节对齐,增加2个8字节
char |||||
int |4 |4 |4 |4 |4 |
double| 8 | 8 | 8 |
int为了能和double对齐,再增加一个4字节
char |||||||||||||||||||||||||
int |4 |4 |4 |4 |4 |4 |
double| 8 | 8 | 8 |
所以sizeof(max)最终值为3 X 8=24字节
再将数组i中的元素数量改为7,看看最终结果
#include<stdio.h>
int main(void)
{
typedef union _DATE{
char a;
int i[7];
double b;
}DATE;
DATE max;
printf("The union DATE sizeof:%d/n/n",sizeof(max));
printf("Int sizeof:%d/n",sizeof(int));
printf("Char sizeof:%d/n",sizeof(char));
printf("Float sizeof:%d/n",sizeof(float));
printf("Double sizeof:%d/n",sizeof(double));
}
运行结果:
The union DATE sizeof:32
Int sizeof:4
Char sizeof:1
Float sizeof:4
Double sizeof:8
max的值为32
Int为4,数组i有7个元素,在内存中的结构为:
char |||||
int |4 |4 |4 |4 |4 |4 |4 |
double| 8 |
但是还有一个double,按8字节对齐,增加3个8字节
char |||||||||||||||||||||||||||||||||
int |4 |4 |4 |4 |4 |4 |4 |
double| 8 | 8 | 8 | 8 |
int为了能和double对齐,再增加一个4字节
char |||||||||||||||||||||||||||||||||
int |4 |4 |4 |4 |4 |4 |4 |4 |
double| 8 | 8 | 8 | 8 |
所以sizeof(max)最终值为4 X 8=32字节