Back
Syntax
Study
Editor
Mode:
HTML
CSS
JavaScript
PHP
Reset
Run »
HTML / CSS / JS
#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) ", 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 ", 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(" Leaderboard: "); for (int i = 0; i < n; i++) printf(" %s: %d pts %.1fs ", leaderboard[i].name, leaderboard[i].score, leaderboard[i].time_sec); /* Struct padding demo */ printf(" sizeof(Point) = %zu ", sizeof(Point)); printf("sizeof(Rectangle) = %zu ", sizeof(Rectangle)); printf("sizeof(Player) = %zu ", sizeof(Player)); return 0; }
Result
Open