Structures
One variable that holds several related values.
5 minute read
Big idea
A structure (struct) bundles several related values — of different types — into one variable.
The idea
A student has a name, a roll number, and a mark. Three separate variables per student gets messy fast. A struct makes them one thing:
struct Student {
char name[20];
int roll;
float mark;
};
That defines a new type called struct Student — a template, not a variable yet. (Note the ; after the closing brace.) Now make variables of it:
struct Student s = {"Asha", 12, 88.5};
Reach each member with a dot:
printf("%s\n", s.name); // Asha
s.mark = 91.0; // change one member
Structs are copied whole
Unlike arrays, you can assign one struct to another with = — every member is copied, even array members:
#include <stdio.h>
struct Point {
int x;
int y;
};
int main(void) {
struct Point a = {1, 2};
struct Point b = a;
a.x = 100;
printf("a=(%d,%d) b=(%d,%d)\n", a.x, a.y, b.x, b.y);
return 0;
}What does it print? Show the answer
a=(100,2) b=(1,2)Run and edit it in the app.
b is its own copy, so changing a afterwards doesn't touch it. The same goes for passing a struct to a function — it gets a copy.
Watch it
Structs and functions
#include <stdio.h>
struct Point {
int x;
int y;
};
struct Point midpoint(struct Point a, struct Point b) {
struct Point m = {(a.x + b.x) / 2, (a.y + b.y) / 2};
return m;
}
int main(void) {
struct Point p = {0, 0}, q = {10, 6};
struct Point m = midpoint(p, q);
printf("(%d, %d)\n", m.x, m.y);
return 0;
}output
(5, 3)Run and edit it in the app.
Think of it like
A form with labelled boxes: Name ____, Roll ____, Mark ____. The struct definition is the blank form; each variable is one filled-in copy.
🕷️ Spidey-sense: My case file on every villain:
struct Villain { char name[30]; char power[40]; int threat_level; };One folder, everything I need.
Key terms
- Structure (
struct) — A type that groups named members. - Member — One named field inside a struct.
.(dot operator) — Reads or writes a member:s.mark.
Check yourself
What does a struct let you do?
How do you read the mark member of a struct variable s?
struct P a = {1, 2}; struct P b = a; a.x = 9; What is b.x?