Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Welcome 🤗! In the next ~4h we will cover:

A footlocker (luggage) from World War 2. A footlocker is to be placed at the foot of a bed, used to store personal belongings.

A footlocker (luggage) from World War 2. A footlocker is to be placed at the foot of a bed, used to store personal belongings.

It is a collection of related items, and each item has its own space inside, which maps nicely onto a struct.

James Emery, CC BY 2.0 Source.

Motivation

Imagine you want to create a program that tracks every student’s data in this classroom:

How would you do this in C?

We used arrays to pack data that have the same type and belong together.

char names[STUDENT_COUNT][NAME_SIZE];
int matriculation_numbers[STUDENT_COUNT];
int birth_years[STUDENT_COUNT];

If you sort names but forget to sort matriculation_numbers the same way, every student now has someone else’s number. Nothing ties names[4], matriculation_numbers[4] etc other than programmer’s discipline! 🙂

structs group these fields into a single unit, so each student’s data stays together by construction:

struct Student {
   char name[NAME_SIZE];
   int matriculation_number, birth_year;
};
struct Student students[STUDENT_COUNT];

Learning goals

Preparation Review

E: Teach your peers

Question pool

Coding

Hello struct union bitfield

Accessing members

Packing four characters in an integer

Shape collage

Workaround for %b on Windows: print_byte_as_bits

Due to lack of support %b in Windows, we have to find our own solution.

I modified the templates. If you already accepted the assignment, copy at the templates of Exercise 2 and Exercise 3 again.

E: Reflection

Let us revisit our learning goals:

Footnotes
  1. A tagged union inside a struct is similar to object-oriented programming. We can have a base class Shape with color, because every shape has a color. Child classes like Circle, Triangle etc can then add their own features like radiusH, size etc.

    Thinking about this design problem made the connection to C++ in my mind, which was very rewarding.