C. 中“联合”和“结构”之间的主要区别是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4003087/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What's the major difference between "union" and "struct" in C.?
提问by Vinay
Possible Duplicate:
Difference between a Structure and a Union in C
可能的重复:
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.?
我可以理解结构的含义。但是,我对 union 和 struct 之间的区别有点困惑。联盟就像是一份记忆。究竟是什么意思。?
回答by Charles Salvia
With a union, all members share the samememory. With a struct, they do not share memory, so a different space in memory is allocated to each member of the struct.
使用联合,所有成员共享相同的内存。对于结构体,它们不共享内存,因此为结构体的每个成员分配了不同的内存空间。
For example:
例如:
union foo
{
int x;
int y;
};
foo f;
f.x = 10;
printf("%d\n", f.y);
Here, we assign the value of 10 to foo::x
. Then we output the value of foo::y
, which is also10 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 largestmember of the union. So a union containing a char
and a long
would need enough space to fit the long
.
在这里,我们将 10 的值分配给foo::x
。然后我们输出 的值foo::y
,它也是10,因为 x 和 y 共享相同的内存。请注意,由于联合的所有成员共享相同的内存,编译器必须分配足够的内存以容纳联合的最大成员。因此,包含 achar
和 a的联合long
需要足够的空间来容纳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);
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.
我们将 10 分配给 x,将 20 分配给 y,然后将它们都打印出来。我们看到 x 是 10,y 是 20,因为 x 和 y 不共享相同的内存。
EDIT: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.
编辑:还要注意上面 Gman 的评论。我随工会提供的示例仅用于演示目的。实际上,您不应该写入联合的一个数据成员,然后访问另一个数据成员。通常这只会导致编译器将位模式解释为另一种类型,但您可能会得到意想不到的结果,因为这样做是未定义的行为。
回答by Sam
I've used unions to convert bytes to and from other types. I find it easier than bit-shifting.
我使用联合来将字节与其他类型相互转换。我发现它比位移更容易。
union intConverter {
int intValue;
struct {
byte hi;
byte lo;
} byteValue;
}
intConverter cv;
cv.intValue =1100;
printf("%X %X\n", cv.byteValue.hi, cv.byteValue.lo);
Where int is 16-bit (was used on a micro controller).
其中 int 是 16 位(用于微控制器)。
回答by Benjamin Lindley
Each member of a union shares the same memory. That means if you change one, you change the others. And if the members are of different types, this can have unpredictable results. (not exactly unpredictable, but hard to predict unless you are aware of the underlying bit patterns that make up the data members).
工会的每个成员共享相同的内存。这意味着如果你改变一个,你就会改变其他的。如果成员的类型不同,这可能会产生不可预测的结果。(并非完全不可预测,但很难预测,除非您了解构成数据成员的底层位模式)。
回答by Eric Towers
It may be more useful to have an uncontrived example of what this is good for. (I say "uncontrived" because most bit-banging uses of union are extremely treacherous. Bit-banging unions taken from big-endian to little-endian hardware break in the most (initially) mystifying ways.) (Of course, I've written bit-banging unions to tear apart floating point numbers to implement orders-of-magnitude-faster-than-the-library math functions. I just add assertions about which members are supposed to have the same addresses.)
有一个非人为的例子来说明这有什么好处可能更有用。(我说“非人为”是因为 union 的大多数 bit-banging 使用都非常危险。从 big-endian 到 little-endian 硬件的 bit-banging union 以最(最初)令人迷惑的方式破坏。)(当然,我已经编写位破坏联合来分解浮点数以实现数量级比图书馆更快的数学函数。我只是添加了关于哪些成员应该具有相同地址的断言。)
struct option1 { int type; /* other members */ }; struct option2 { int type; /* other members */ }; struct option3 { int type; /* other members */ }; union combo { int type; // guaranteed to exactly overlap with the structs' ints type. struct option1; struct option2; struct option3; }; // ... void foo(union combo *in) { switch(in.type) { case 1: { struct option1 *bar = in; //then process an option1 type of request } case 2: { struct option2 *bar = in; //then process an option2 type of request } case 3: { struct option3 *bar = in; //then process an option3 type of request } }
This kind of construction is very common in X programming and other situations where one wishes to make a function that can receive many different types of messages (with different argument and layout requirements).
这种构造在 X 编程和其他希望创建一个可以接收许多不同类型消息(具有不同参数和布局要求)的函数的情况下非常常见。
回答by Jeff Mercado
I suppose one way you can think of a union is that it is a set of aliases of varying type to a block of memory where each member of the union is an "alias" with a given type. Each alias refers to the same address in memory. How the bits at that address are interpreted are determined by the alias' type.
我想你可以想到联合的一种方式是,它是一组不同类型的别名到一块内存,其中联合的每个成员都是给定类型的“别名”。每个别名引用内存中的相同地址。如何解释该地址的位由别名的类型决定。
The amount of memory the union occupies is always equal to or possibly larger than the largest sized "member" of the union (due to alignment restrictions).
联合占用的内存量总是等于或可能大于联合的最大“成员”(由于对齐限制)。
回答by Manoj R
Run this program and find out the output.
运行这个程序并找出输出。
#include < stdio.h >
#include <stdio.h>
int main() { union _testUnion { long long x; long long y; } testUnion; struct _testStruct { long long x; long long y; }testStruct; printf("Sizeof Union %d\n",sizeof(testUnion)); printf("Sizeof Struct %d\n",sizeof(testStruct)); return; }
You will find that the size of struct is double than that of union. This is because union has allocated space for only one variable while struct has allocated for two.
你会发现 struct 的大小是 union 的两倍。这是因为 union 只为一个变量分配了空间,而 struct 为两个变量分配了空间。
回答by Manoj R
Most answers here are correct. A union is essentially a way to access same data in different ways (For example, you can access/interpret 4 bytes of memory as 1 integers, or as 4 characters). Structs as you know are straightforward - a collection of different, seprate objects with their own memory.
这里的大多数答案都是正确的。联合本质上是一种以不同方式访问相同数据的方式(例如,您可以将 4 个字节的内存访问/解释为 1 个整数或 4 个字符)。如您所知,结构很简单 - 具有自己内存的不同对象的集合。
Usually you require Unions at a much later stage in programming as compared to Structs.
与结构体相比,通常在编程的后期阶段需要联合体。