1.

What is the difference between struct and union in C?

Answer»

A struct is a group of complex data structures stored in a block of memory where each MEMBER on the block gets a separate memory location to make them accessible at once

Whereas in the union, all the member variables are stored at the same location on the memory as a result to which while assigning a value to a member variable will CHANGE the value of all other members.

/* struct & union definations*/struct bar { int a; // we can use a & B both SIMULTANEOUSLY char b;} bar;union foo { int a; // we can't use both a and b simultaneously char b;} foo;/* using STRUC and union variables*/struct bar y;y.a = 3; // OK to usey.b = 'c'; // OK to useunion foo x;x.a = 3; // OKx.b = 'c'; // NOl this affects the value of x.a!


Discussion

No Comment Found