C Structures and Unions
Ad
Structures
A struct groups related variables of different types into one custom type.
struct Point {
int x;
int y;
};
struct Point p = {10, 20};
printf("%d, %d", p.x, p.y); // 10, 20
typedef for Cleaner Code
typedef struct {
char name[50];
int age;
} Person;
Person sara = {"Sara", 25};
Unions
A union stores different types in the same memory — only one member is valid at a time, saving memory.
union Value {
int i;
float f;
char c;
};
// sizeof(union) = size of its largest member
Struct vs Union
| Struct | Union | |
|---|---|---|
| Memory | Sum of members | Largest member |
| Members usable | All at once | One at a time |
FAQs
When use a union?
When a value can be one of several types but never more than one at a time — saves memory. More in our C guides.
Access struct via pointer?
Use the arrow operator: ptr->x.
