Challenge - 5 Problems
Union Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of union member assignment
What is the output of this C program?
C
#include <stdio.h>
union Data {
int i;
float f;
char str[20];
};
int main() {
union Data data;
data.i = 10;
data.f = 220.5f;
printf("%d\n", data.i);
return 0;
}Attempts:
2 left
💡 Hint
Remember that all members of a union share the same memory space.
✗ Incorrect
In a union, all members share the same memory. Assigning to data.f overwrites data.i. Printing data.i after assigning data.f will show an unpredictable integer value representing the float bits.
❓ Predict Output
intermediate2:00remaining
Size of union vs struct
What will be the output of this program?
C
#include <stdio.h>
union U {
int i;
double d;
char c;
};
struct S {
int i;
double d;
char c;
};
int main() {
printf("%zu %zu\n", sizeof(union U), sizeof(struct S));
return 0;
}Attempts:
2 left
💡 Hint
Union size is the size of its largest member; struct size is sum plus padding.
✗ Incorrect
The union size equals the largest member size (double = 8 or 16 bytes depending on platform, here 16). The struct size is sum of members plus padding, here 24 bytes.
🔧 Debug
advanced2:00remaining
Why does this union code cause unexpected output?
Consider this code snippet. Why does printing data.str after assigning data.i show unexpected characters?
C
#include <stdio.h>
#include <string.h>
union Data {
int i;
char str[4];
};
int main() {
union Data data;
data.i = 0x41424344; // Hex for 'ABCD'
printf("%s\n", data.str);
return 0;
}Attempts:
2 left
💡 Hint
Think about how strings are represented in C and what printf expects.
✗ Incorrect
The char array in the union is not null-terminated after assigning the integer. printf expects a null-terminated string, so it reads past the array causing garbage output.
🧠 Conceptual
advanced2:00remaining
Union member alignment and padding
Which statement about union member alignment and padding is true?
Attempts:
2 left
💡 Hint
Think about how unions share memory and how alignment affects size.
✗ Incorrect
Unions share the same memory for all members. The size is the largest member size, rounded up to meet the strictest alignment requirement among members.
❓ Predict Output
expert2:00remaining
Output of union with bit fields and overlapping members
What is the output of this program?
C
#include <stdio.h>
union U {
struct {
unsigned int a:4;
unsigned int b:4;
} bits;
unsigned char byte;
};
int main() {
union U u;
u.byte = 0;
u.bits.a = 9; // 1001 in binary
u.bits.b = 6; // 0110 in binary
printf("%u\n", u.byte);
return 0;
}Attempts:
2 left
💡 Hint
Calculate the bits: a in lower 4 bits, b in upper 4 bits.
✗ Incorrect
Bits a=9 (1001) in lower 4 bits, b=6 (0110) in upper 4 bits. Combined byte = 01101001 binary = 0x69 = 105 decimal.