struct和union的区别
2016-08-09 16:27
337 查看
1)union是几个不同类型的变量共占一段内存(相互覆盖);struct是把不同类型的数据组合成一个整体
2)对齐方式略有区别;union不需要+,只需要拿出对齐后的最长
2)对齐方式略有区别;union不需要+,只需要拿出对齐后的最长
structure | union |
---|---|
Keyword structdefines a structure. | Keyword uniondefines a union. |
Example structure declaration:struct s_tag { int ival; float fval; char *cptr; }s; | Example union declaration:union u_tag { int ival; float fval; char *cptr; }u; |
Within a structure all members gets memory allocated and members have addresses that increase as the declarators are read left-to-right. That is, the members of a structure all begin at different offsets from the base of the structure. The offset of a particular member corresponds to the order of its declaration; the first member is at offset 0. The total size of a structure is the sum of the size of all the members or more because of appropriate alignment. | For a union compiler allocates the memory for the largest of all members and in a union all members have offset zero from the base, the container is big enough to hold the WIDEST member, and the alignment is appropriate for all of the types in the union. When the storage space allocated to the union contains a smaller member, the extra space between the end of the smaller member and the end of the allocated memory remains unaltered. |
Within a structure all members gets memory allocated; therefore any member can be retrieved at any time. | While retrieving data from a union the type that is being retrieved must be the type most recently stored. It is the programmer's responsibility to keep track of which type is currently stored in a union; the results are implementation-dependent if something is stored as one type and extracted as another. |
One or more members of a structure can be initialized at once. | A union may only be initialized with a value of the type of its first member; thus union udescribed above (during example declaration) can only be initialized with an integer value. |
相关文章推荐
- strlen与sizeof区别(转载)以及struct,union的sizeof内存对齐等问题
- 大端小端区别、Union和Struct的内存分配
- C++中的共用体(union)结构解析与结构体(struct)共用体(union) 的区别
- 联合体(union)和结构体(struct)的区别
- 联合体(union)和结构体(struct)的区别
- 大端小端区别、Union和Struct的内存分配、对齐方式
- union 与struct 区别简介
- C语言中union与struct的区别及sizeof的计算方式
- 联合体(union)和结构体(struct)的区别
- struct 与 union 的区别
- 神秘的sizeof(union和struct的区别)
- Union和struct的内存分配区别
- C中的union和struct的区别
- (转载)C中的union和struct的区别,为什么要发明union?
- union 与 struct 区别
- union和struct的区别
- 大小端区别、Union和Struct的内存大小
- Struct 和 Union区别
- union和struct区别
- class struct union 的区别