Lesson 24 / 36
Structures
Group related values of different types under one name.
A custom, composite type
A struct bundles multiple fields — possibly of different types — into one unit, unlike an array which holds same-typed values.
Define, create, access
Fields are accessed with the dot operator ..
struct Point {
int x;
int y;
};
int main(void) {
struct Point p1 = {3, 4};
printf("(%d, %d)\n", p1.x, p1.y);
p1.x = 10;
return 0;
}
Output:
(3, 4)
Structs can nest
A struct field can itself be another struct — access chains with multiple dots.
struct Address { char city[20]; };
struct Person {
char name[20];
struct Address addr;
};
struct Person p = {"Riya", {"Pune"}};
printf("%s lives in %s\n", p.name, p.addr.city);
Output:
Riya lives in Pune