+ 21
What is the difference between structure and union?
8 ответов
+ 14
A structure is a class, basically. Or if we go a bit more oldschool (C), it's simply a collection of values. This example
struct { int a; int b; } s;
s.a = 4;
s.b = 3;
cout << s.a << ", " << s.b << endl;
will output "4, 3". So far so obvious!
Unions are different, in that all the members of a union occupy the same place in memory. That means if we change our struct to
union { int a; int b; } s;
and run the above code again, we will see "3, 3". `a` and `b` point to the same place in memory, so changing one will change the other. This might seem a bit pointless and a union of two ints probably is, but there are a few use cases. If you are just starting out I don't recommend using unions and they're mostly a C thing so you probably won't need them in C++ at all, but here's an example:
union {
int coordinates[2];
struct {
int x;
int y;
};
} s;
s.x = 4;
cout << s.coordinates[0] << endl;
This will print "4"! The struct and the array point to the same place in memory, so this works (at least on most systems).
I guess it's good to have heard about unions, but they aren't the most important thing in the world. You usually use them when dealing with rather low-level and exotic stuff, so don't worry about them too much. You'll need to have a firm grasp on pointers before fully getting what's going on I think :)
+ 13
Thank you dude
+ 8
Structure can share memory has a one block only but union share has various block in one memory block
+ 5
alguien habla español?
+ 3
A union allows to store different data types in the same memory location.
It is like a structure because it has members. However, a union variable uses the same memory location for all its member's and only one member at a time can occupy the.
A union declaration uses the keyword union, a union tag, and curly braces { } with a list of members.
Union members can be of any data type, including basic types, strings, arrays, pointers, and structures.
+ 2
In a language like COBOL a structure is called a record while a union is accomplished with the REDEFINES keyword making it more obvious that the structure contains contiguous data fields (variables) while unions contain overlapping variables.
In a table format it would look like this:
STRUCTURE
Start length. Variable
1. 1. Char
2. 5. Int
But a UNION would look like this:
Start length variable
1. 1. Char
1. 4. Int.
Putting 'x' in the char and 1 in the int would result in the char containing 'x' in the struct, but would change its value in the union.
+ 2
In the structure all variables occupied the some bite of memory but in union the memory will be execute only big size of variable and all other rest is joint them.
0
Wt about size of the both