#include <stdio.h>
struct Data {
int i;
char c;
double d;
};
int main() {
struct Data s = {5, 'A', 3.14};
printf("%d %c %.2f\n", s.i, s.c, s.d);
printf("Size of struct Data: %zu\n", sizeof(s));
return 0;
}The structure contains an int (4 bytes), a char (1 byte), and a double (8 bytes). Due to alignment, padding bytes are added so the double starts at an 8-byte boundary. This makes the total size 16 bytes on most systems.
#include <stdio.h>
union Value {
int i;
float f;
};
int main() {
union Value v;
v.i = 1065353216;
printf("%d %.2f\n", v.i, v.f);
return 0;
}The integer 1065353216 has the same bit pattern as the float 1.0 in IEEE 754 format. So printing the float member shows 1.00.
#include <stdio.h>
union Data {
int i;
char str[4];
};
int main() {
union Data d;
d.i = 0x41424344;
printf("%d %c %c %c %c\n", d.i, d.str[0], d.str[1], d.str[2], d.str[3]);
return 0;
}Unions share the same memory for all members. Assigning to the int sets the bytes, which the char array then interprets as characters. The order depends on whether the system is little-endian or big-endian.
Option D uses designated initializer syntax to initialize the union member correctly at declaration. Other options have syntax errors or invalid assignments.
struct S {
char c;
int i;
double d;
};
union U {
char c;
int i;
double d;
};The struct has a char (1 byte), then padding (3 bytes), then int (4 bytes), then double (8 bytes), totaling 16 bytes due to alignment. The union size equals the largest member size, which is double (8 bytes).