Unions
Completed
A union Value { int i; char c; }; holds one of its members at a time. For each input i N or c X, store it in the right member and print int N or char X, plus sizeof(union Value) at the end.
Input
n, then n lines.
Output
n lines, then the size.
Example
Input
3 i 42 c Z i -7
Output
int 42 char Z int -7 4
Editor
C
Hints
All members of a union share the same memory; its size is the size of the largest member.
Solution explanation
Unions save memory when only one of several types is needed at a time.
Show solution
#include <stdio.h>
union Value {
int i;
char c;
};
int main() {
int n;
char kind;
union Value v;
scanf("%d", &n);
for (int k = 0; k < n; k++) {
scanf(" %c", &kind);
if (kind == 'i') {
scanf("%d", &v.i);
printf("int %d\n", v.i);
} else {
scanf(" %c", &v.c);
printf("char %c\n", v.c);
}
}
printf("%d\n", (int) sizeof(union Value));
return 0;
}