Summary
In this lesson, you learned that:
- A structure groups values that belong together, even of different types, into one whole. Its definition lists its members and ends with
};, the semicolon included. - A variable of a structure type is created with its values in curly braces, in the order of the members:
struct product bread = {"Bread", 32.5, 2};. - You get to a member with a dot,
bread.price, and use it like an ordinary variable. Text is copied into a member withstrcpy, because an array can't be assigned with=. typedef struct { ... } Product;gives the type the nameProduct, so you writeProduct bread. This course writes structures this way.- An array of structures,
Product cart[3], holds a structure in each element:cart[i].name. Widths such as%-8sand%6.2fline up the columns of a table. - A member can be an array or another structure, and you chain the dots and brackets:
eva.birthday.year,eva.points[0]. - A structure passed to a function is copied, and so is a structure assigned with
=. Changes to the copy don't change the original. Structures can't be compared with==; compare their members. - Through a pointer,
Product *item, a function changes the original:item->countis the same as(*item).count, and you call it with&milk.const Product *itemis for a function that only reads. - A function can return a structure, and so give back several values at once.
That was the last new topic of the course. In the next lesson, the final project, you will write one bigger program step by step and use everything you have learned: variables, conditions, loops, arrays, strings, functions, pointers and structures.
But first, practice structures on a small task: a reading list.
Instructions
Above main, define with typedef a structure Book with three members: the title title (an array of 30 characters) and two whole numbers, the number of pages pages and the number of pages you have already read, pages_read. In main, create an array books with three books: The Hobbit with 310 pages, 120 of them read; Matilda with 240 pages, none read; and Momo with 300 pages, all of them read. Then print the books with a loop, one per line, as The Hobbit: 120/310.
Between the structure and main, write a function void read_pages(Book *book, int count) that adds count to the book's pages_read, but never more pages than the book has: if the result is bigger than pages, it sets pages_read to pages. In main, before the loop, call it twice: read_pages(&books[0], 250) and read_pages(&books[1], 35). The program then prints The Hobbit: 310/310, Matilda: 35/240 and Momo: 300/300.
Start programming for free
9/9