欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

C/C++ union size

程序员文章站 2022-07-04 08:12:30
...
C/C++,对于union的 size,普遍说法是,union的大小和其所包含的成员中size最大的members一致。
int main(void){
union u_tag {
	char a[13];
	int i;
}u;
printf("%d",sizeof(u));
 return 0;
}

很快可以看出,此union中,其size最大的member是 char a[13],为 13 bytes。
但是其union的size 却是 16。

union在本质上是 variable。
The C programming language 写道
A union is a variable that may hold (at different times) objects of different types and sizes,
with compiler keeping track of size and alignment requirements

分析一个variable,需要不仅要分析其在内存中所占的大小,即 size,还要分析其在内存中的对齐方式,即 alignment。

union u最少需要分配需13 bytes的内存空间,这样才既可以存储char a[13],又有足够空间来存储 int i。
对任何一种 varaible都有 默认的alignment 要求,比如int型 的alignment是4 bytes,char是1 bytes. union也不例外,其alignment要和其成员中alignment值最大的成员保持一致。在上面的例子,union u的alignment需要和int i的alignment一致。即4 bytes.
所以union在分配13 bytes的 内存空间的同时,还需要在最后padding(填补) 3个无意义的bytes来满足 4-bytes的alignment的要求(size为4的整数倍)所以其size为16 bytes。

在内存中分析union时,只需要分析union中,所占size最大的成员和alignment值最大的成员,如定义所说的既要满足size requirement 又要满足 alignment requirement.

http://chuansu.iteye.com/blog/1487350这里对 data alignment以及struct size有很好的诠释。
int main(void){

union u_tag {
	char a[13];
	int i;
};
struct tt{
		short d;
		union u_tag u;
	}t;
printf("%d",sizeof(t));
 return 0;
}


struct t 的成员中包含 union u。 由于union u的alignment为4,在内存中,u与short d之间需要填补两个bytes来满足 union u的offset是 其alignment的整数倍。
最后需要看看struct内所有member的总size是不是为 此struct alignment的整数倍,在这里struct t的alignment就是union u的alignment(与其alignment值最大的成员保持一致).
所以最后结果为 sizeof(short d)+2 padding bytes +sizeof(union u)=20。

union与struct的区别

首先 union仅仅为一个variable 而struct则是 a collection of variables,是集合。
union在内存中,每一个成员或者variable都是起始于同一位置,或者说其所有的member的offset是一样的。这也是为什么union一次只能存储一个variable的原因。而struct中的成员显然不是。
引用
In effect, a union is a structure in which all memebers have offset zero from the base, the structure is big enough to hold the "widest" memeber and the alignment is appropriate for all of the types in the union.