Learn C · lesson 37 of 60 · about 7 minutes
Defining Structs
Describe the disks in the report: group related values into your own type with struct, and read and set its members.
What you'll learn
- Define a struct type
- Create and initialise a struct
- Access members with the dot operator
The disks
The report knows the main disk's size and how much of it is used, but those are two loose variables. Now the admin can plug in a USB stick too, and every disk has the same three facts: a name, a size and how much is used. A struct Disk bundles them, so main_disk and usb are two values of the same new type. The stick's sizes are read straight into its members with scanf("%d %d", &usb.size_kib, &usb.used_kib), then checked before they're printed.
Your own types
A struct bundles several values, called members, into one new type. A player might have a name, a level and some XP:
struct Player { char name[20]; int level; double xp; };
Then struct Player p; makes one player, and p.level reaches inside it.
A player struct
#include <stdio.h>
struct Player {
char name[20];
int level;
double xp;
};
int main(void) {
struct Player p = {"Phoebe", 3, 125.5};
printf("%s is level %d with %.1f XP\n", p.name, p.level, p.xp);
p.level++;
p.xp += 50;
printf("Now level %d, %.1f XP\n", p.level, p.xp);
return 0;
}Output
Phoebe is level 3 with 125.5 XP
Now level 4, 175.5 XPCopies and designated initialisers
Assigning one struct to another copies all its members. You can also name members when initialising: {.level = 1, .xp = 0}; anything you leave out becomes zero.
Copying a struct
#include <stdio.h>
struct Point {
int x;
int y;
};
int main(void) {
struct Point a = {.x = 2, .y = 5};
struct Point b = a;
b.x = 10;
printf("a=(%d,%d) b=(%d,%d)\n", a.x, a.y, b.x, b.y);
return 0;
}Output
a=(2,5) b=(10,5)Tip
Don't forget the semicolon after a struct definition's closing brace. It's one of the most common C compile errors.
Now try it yourself
This lesson is free in Codiqo, with 10 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.