C
Beginner
1 min read
Nested Structs and Arrays of Structs
Example
#include <stdio.h>
#include <string.h>
typedef struct {
double x, y;
} Point;
typedef struct {
Point top_left;
Point bottom_right;
char label[32];
} Rectangle;
typedef struct {
char name[32];
int score;
double time_sec;
} Player;
void print_rect(const Rectangle *r)
{
printf("Rect '%s': (%.1f,%.1f)-(%.1f,%.1f)\n",
r->label,
r->top_left.x, r->top_left.y,
r->bottom_right.x, r->bottom_right.y);
}
int main(void)
{
/* Nested struct initialisation */
Rectangle r = {
.top_left = {0.0, 10.0},
.bottom_right = {20.0, 0.0},
.label = "viewport"
};
print_rect(&r);
/* Accessing nested members */
double width = r.bottom_right.x - r.top_left.x;
double height = r.top_left.y - r.bottom_right.y;
printf("Size: %.1f x %.1f\n", width, height);
/* Array of structs */
Player leaderboard[] = {
{"Alice", 9500, 123.4},
{"Bob", 8700, 145.2},
{"Carol", 9900, 98.6}
};
int n = sizeof(leaderboard) / sizeof(leaderboard[0]);
printf("\nLeaderboard:\n");
for (int i = 0; i < n; i++)
printf(" %s: %d pts %.1fs\n",
leaderboard[i].name,
leaderboard[i].score,
leaderboard[i].time_sec);
/* Struct padding demo */
printf("\nsizeof(Point) = %zu\n", sizeof(Point));
printf("sizeof(Rectangle) = %zu\n", sizeof(Rectangle));
printf("sizeof(Player) = %zu\n", sizeof(Player));
return 0;
}