什么是之间和QUOT的主要区别;工会"和"结构"在C? [英] What's the major difference between "union" and "struct" in C.?

查看:166
本文介绍了什么是之间和QUOT的主要区别;工会"和"结构"在C?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:结果
  <一href=\"http://stackoverflow.com/questions/346536/difference-between-a-structure-and-a-union-in-c\">Difference用C 一个结构和联盟之间的

Possible Duplicate:
Difference between a Structure and a Union in C

我能理解什么是结构的意思。但是,我与工会和结构之间的区别有点混乱。联盟就像一个内存份额。它到底是什么意思?

I could understand what a struct means. But, i am bit confused with the difference between union and struct. Union is like a share of memory. What exactly it means.?

推荐答案

通过工会,所有成员共享的相同的内存。有了一个结构,它们不共享内存,所以在内存中不同的空间分配给该结构中的每个成员。

With a union, all members share the same memory. With a struct, they do not share memory, so a different space in memory is allocated to each member of the struct.

例如:

union foo
{
 int x;
 int y;
};

foo f;
f.x = 10;
printf("%d\n", f.y);

在这里,我们的10值分配给 :: foo的X 。然后,我们输出的价值富::是,这是的10,因为x和y共享相同的内存。请注意,由于工会共享相同的内存中的所有成员,编译器必须分配足够的内存,以适合的最大的工会成员。因此,含工会字符将需要足够的空间,以适应

Here, we assign the value of 10 to foo::x. Then we output the value of foo::y, which is also 10 since x and y share the same memory. Note that since all members of a union share the same memory, the compiler must allocate enough memory to fit the largest member of the union. So a union containing a char and a long would need enough space to fit the long.

但是,如果我们使用结构:

But if we use a struct:

struct foo
{
 int x;
 int y;
};

foo f;
f.x = 10;
f.y = 20;
printf("%d %d\n", f.x, f.y);

我们指定10 x和20到y,然后打印他们两个。我们看到,x为10和y为20,因为x和y不共享相同的存储器

We assign 10 to x and 20 to y, and then print them both out. We see that x is 10 and y is 20, because x and y do not share the same memory.

编辑:同时注意GMAN的评论以上。我提供了与工会的例子是仅用于演示目的。在实践中,你不应该写一个联合的一个数据成员,然后访问另一个数据成员。通常这只会导致编译器间preT的位模式为另一种类型,但由于这样做,你可能会得到意外的结果是的未定义行为

Also take note of Gman's comment above. The example I provided with the union is for demonstration purposes only. In practice, you shouldn't write to one data member of a union, and then access another data member. Usually this will simply cause the compiler to interpret the bit pattern as another type, but you may get unexpected results since doing this is undefined behavior.

这篇关于什么是之间和QUOT的主要区别;工会&QUOT;和&QUOT;结构&QUOT;在C?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆