Saturday 22 November 2014

Difference between Structure and Union

vishalgarg837@gmail.com

Difference between Structure and Union

 Basically I know that struct uses all the memory of its member and union uses the largest members memory space.
With a union, you're only supposed to use one of the elements, because they're all stored at the same spot. This makes it useful when you want to store something that could be one of several types. A struct, on the other hand, has a separate memory location for each of its elements and they all can be used at once.

e.g.

union test {
  int a;   // can not use both a and b at once
  char b;
} test;
Here union will need 4 bytes memory.2 bytes for int & 2 bytes for char. 

struct fun {
  int a;   // can use both a and b simultaneously
  char b;
} fun;
Here structure will need 3 bytes memory.2 bytes for int & 1 byte for char. 

union test x;
x.a = 3; // OK
x.b = 'c'; // NO this affects the value of x.a

struct fun y;
y.a = 3; // OK
y.b = 'c'; // OK