Topic 8 of 15 · Intermediate
Structures, Unions & Enums
Group related data and understand padding.
Concept
A struct groups fields of different types. Access with . on a variable and -> through a pointer.
The compiler adds padding so fields are aligned, so sizeof(struct) can be larger than the sum of its fields. Order fields large-to-small to reduce padding.
A union shares one memory area among all members (size = largest member). enum gives names to integer constants. typedef creates a type alias.
Code (C17)
#include <stdio.h>
typedef struct {
int id;
char name[20];
double cgpa;
} Student;
union Value { int i; float f; char c; };
enum Level { BEGINNER, INTERMEDIATE, EXPERT };
int main(void) {
Student s = {1, "Asha", 8.7};
Student *p = &s;
p->cgpa = 9.1;
printf("%s %.1f\n", s.name, s.cgpa);
printf("sizeof Student = %zu, union = %zu\n", sizeof(Student), sizeof(union Value));
enum Level lv = EXPERT;
printf("%d\n", lv); // 2
return 0;
}Remember
- -> is (*p).field.
- Padding affects sizeof.
- Only one union member is valid at a time.
Interview questions
struct vs union?
A struct allocates space for every member; a union shares one space sized to its largest member.
Why is sizeof(struct) bigger than expected?
Alignment padding inserted between/after members so each starts at an address suited to its type.
Lesson test
Take an 8-question test on “Structures, Unions & Enums” — concepts, output prediction, bug spotting and interview questions.