您的位置:首页 > 其它

结构和联合的区别

2010-12-04 10:02 176 查看

结构和联合的区别 (转)

1. 联合说明和联合变量定义
联合也是一种新的数据类型, 它是一种特殊形式的变量。
联合说明和联合变量定义与结构十分相似。其形式为:
union 联合名{
数据类型 成员名;
数据类型 成员名;
...
} 联合变量名;
联合表示几个变量公用一个内存位置, 在不同的时间保存不同的数据类型
和不同长度的变量。
下例表示说明一个联合a_bc:
union a_bc{
int i;
char mm;
};
再用已说明的联合可定义联合变量。
例如用上面说明的联合定义一个名为lgc的联合变量, 可写成:
union a_bc lgc;
在联合变量lgc中, 整型量i和字符mm公用同一内存位置。
当一个联合被说明时, 编译程序自动地产生一个变量, 其长度为联合中最大
的变量长度。
2 结构和联合有下列区别:
1. 结构和联合都是由多个不同的数据类型成员组成, 但在任何同一时刻,
联合中只存放了一个被选中的成员, 而结构的所有成员都存在。
2. 对于联合的不同成员赋值, 将会对其它成员重写, 原来成员的值就不存
在了, 而对于结构的不同成员赋值是互不影响的。

=======Difference With example======

Lets say a structure containing an int,char and float is created and a union containing int char float are declared. struct TT{ int a; float b; char c; } Union UU{ int a; float b; char c; }

sizeof TT(struct) would be >9 bytes (compiler dependent-if int,float, char are taken as 4,4,1)

sizeof UU(Union) would be 4 bytes as supposed from above.If a variable in double exists in union then the size of union and struct would be 8 bytes and cumulative size of all variables in struct.

Detailed Example:

struct foo
{
char c;
long l;
char *p;
};

union bar
{
char c;
long l;
char *p;
};

A struct foo contains all of the elements c, l, and p. Each element is
separate and distinct.

A union bar contains only one of the elements c, l, and p at any given
time. Each element is stored in the same memory location (well, they all
start at the same memory location), and you can only refer to the element
which was last stored. (ie: after "barptr->c = 2;" you cannot reference
any of the other elements, such as "barptr->p" without invoking undefined
behavior.)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: