Govt. Exams
Entrance Exams
union Test {
int a[5];
char b[10];
double c;
}
Union size equals the largest member. int[5] = 20 bytes, char[10] = 10 bytes, double = 8 bytes. Maximum is 20 bytes.
union Data {
int a;
char b;
};
union Data d;
d.a = 257;
printf("%d %c", d.a, d.b);
Union shares memory. 257 in int format overwrites the char. On a little-endian system, only the lower byte (1) is stored in the char portion.
struct Point {
char c;
int x;
double y;
}
char(1) + padding(3) + int(4) + double(8) = 16 bytes minimum, but alignment to double boundary makes it 24 bytes.
Use dot operator (.) for direct structure variables and arrow operator (->) for pointers, or combinations for nested access.
Reading a union member that wasn't last written gives unpredictable results (garbage value or leftover bits from previous member).
typedef struct creates a type alias, allowing you to declare variables without using the 'struct' keyword each time.
A union is the appropriate choice when you need to store different data types but only one value at a time.
Unions are primarily used in embedded systems to conserve memory by allowing multiple members to share the same memory location.
Both nested structure definitions (defining B inside A and declaring B as member) are valid in C.
In C, you can assign one structure variable to another of the same type, and all members are copied (shallow copy).