Lesson 17 · 17 of 20
Structs · C
Group related data into a C struct: a shop's products with a name, price and stock, the dot, the arrow and pointers to structs.

A structure (struct) puts several related pieces of data into one type, each with its own name and type. struct Product has three fields: name, price and stock. It is C's way of describing "a product".
To create one, give the values between braces in the same order as the fields, as with mug, or by name, as with lamp: .name = "Lamp". The dot reaches each field: mug.price = 6.95 changes the price. A text field would be changed with strcpy, like any string.
show takes the struct by value, that is, a copy: enough to read it. sell, on the other hand, has to change the stock, so it takes a pointer: sell(&mug, 5). With a pointer to a struct, fields are reached with the arrow: p->stock is the same as (*p).stock.
sell will not sell more than there is: with 4 lamps asked for and 3 in stock, it adjusts units and the lamp ends up at 0.
Code · main.c
#include <stdio.h>// A struct groups related data under one name.struct Product { char name[20]; double price; int stock;};void show(struct Product p) { // gets a copy: enough to read it printf("%-10s %6.2f stock %2d\n", p.name, p.price, p.stock);}// A pointer lets the function change the struct; -> reaches its fields.void sell(struct Product *p, int units) { if (units > p->stock) units = p->stock; p->stock -= units; printf("Sold %d x %s\n", units, p->name);}int main(void) { struct Product mug = {"Mug", 7.50, 12}; struct Product lamp = {.name = "Lamp", .price = 24.90, .stock = 3}; mug.price = 6.95; // the dot reaches each field show(mug); show(lamp); sell(&mug, 5); sell(&lamp, 4); // only 3 left show(mug); show(lamp); return 0;}Output · cc main.c -o main && ./main
Mug 6.95 stock 12 Lamp 24.90 stock 3 Sold 5 x Mug Sold 3 x Lamp Mug 6.95 stock 7 Lamp 24.90 stock 0
Key points
- A
structgroups several fields into one type. variable.fieldreads or changes a field.- Pass a pointer so the function can change the struct.
p->fieldis(*p).field.- You can initialise by order or with
.field = value.
Exercise
Write void restock(struct Product *p, int units) that adds stock, and a double stock_value(struct Product p) function that returns price times stock; use them on both products.