Do you guys use unions often in your programs?
: : Please explain the difference between a struct and a union in a demo program.
: :
: : Thank you!Gamemania
: :
: : Planet of Wonders (
http://tech-war.virtualave.net/ )
: :
: Unions all share the same space in memory. Writing to one of its members could overwrite one or all of the other members. A union is as big as its biggest member. For example (I assume you're using a compiler/whatever that has the sizes I'm used to for its variables):
:
: union {
: double D; // 64 bits
: float F; // 32 bits
: short S; // 16 bits
: unsigned char C; // 8 bites
: } MyUnion;
:
: int Size = sizeof(MyUnion); // Size == 64
:
:
: If you set MyUnion.D equal to 50.2 then it would overwrite all of the other variables.
:
: A struct has each variable packeted into a single block of memory (not always consecutively though). So, if we did this:
:
: struct {
: double D; // 64 bits
: float F; // 32 bits
: short S; // 16 bits
: unsigned char C; // 8 bites
: } MyStruct;
:
: int Size = sizeof(MyStruct); // Size == 120
: // I assume no byte alignment is done to the struct
:
: Obviously writing to one member of the struct doesn't overwrite the others (under normal circumstances). So they all have their own memory and don't share it.
:
:
http://druidgames.cjb.net
:
:
Gamemania
Planet of Wonders (
http://tech-war.virtualave.net/ )