← Back to C Course Foundations
Structure and Union (C)¶
Learning Objectives¶
- Define and initialize structures and unions.
- Access members correctly.
- Explain memory difference between structure and union.
Concept¶
struct: each member gets separate memory.union: all members share the same memory block.
C Example¶
#include <stdio.h>
#include <string.h>
typedef struct {
int id;
char name[20];
float marks;
} Student;
typedef union {
int i;
float f;
char ch;
} Data;
int main(void) {
Student s1 = {101, "Riya", 89.5f};
printf("Student -> id=%d name=%s marks=%.1f\n", s1.id, s1.name, s1.marks);
Data d;
d.i = 65;
printf("Union as int: %d\n", d.i);
d.f = 10.5f;
printf("Union as float: %.2f\n", d.f);
printf("Size of Student: %lu\n", sizeof(Student));
printf("Size of Data union: %lu\n", sizeof(Data));
return 0;
}
Dry Run Insight¶
Studentretains all fields simultaneously.- In
union Data, writingd.foverwrites previously storedd.i.
Common Mistakes¶
- Expecting union members to hold independent values.
- Forgetting
.operator for structure member access. - Missing
typedefconsistency.
Practice¶
- Create
Employeestructure. - Create union for sensor value (
intorfloat). - Compare memory sizes of both.