CS210 · Block 3 · Lesson 18

Structs Introduction

User-defined types · struct · dot operator · enum · typedef · struct copy
At a glance: Your first user-defined type. Block 3 opens with structs: how to bundle several related values into one named type, how to access the parts, and the two small tools (enum and typedef) that make struct heavy code readable. The walkthrough in Section 5 builds a Pokemon type and uses it; the lab applies the same pattern to your own design.
Contents
  1. Lesson Objectives
  2. Assigned Readings
  3. Pre-Class Work
  4. Lesson Materials and Overview
  5. In-Class Work
  6. After Class
1. Lesson Objectives

By the end of this lesson, cadets will be able to:

  1. Define struct types to group related data. (Outcome 2)
  2. Declare struct variables and access their members with the dot operator. (Outcome 2)
  3. Apply enum and typedef to create readable user-defined types. (Outcome 2)
2. Assigned Readings

Complete before class. These set the vocabulary we will use.

Source Sections Why
Beej-C Chapter 8 (Structs) Defining structs, dot operator, initialization
Beej-C Chapter 10 (typedef) Skim. Focus on aliasing struct types; you will use this in the walkthrough and lab.
King, C Programming: A Modern Approach Chapter 16 (Structures, Unions, and Enumerations) Optional deeper coverage of enum and typedef
3. Pre-Class Work
Do this first
Plan on 30 to 45 minutes. The reading is short; budget time for the predict step at the bottom.

Pre-Class Checklist

1
Read Beej-C Chapter 8 (Structs)
Read the first parts that introduce struct definitions, the dot operator, designated initializers, and copying structs with =. You can skim the section on pointers to structs and the arrow operator; that is Lesson 19.
Terms to know going in: struct, member, field, enum, typedef.
2
Predict before you press Enter
Read this small program and predict what gets printed before you check the answer below.
struct Point { int x; int y; };

struct Point a = { 3, 4 };
struct Point b = a;
b.x = 99;
printf("%d %d\n", a.x, b.x);
Click for the answer
Prints 3 99. When you write b = a, C copies every field of a into b. Once that copy is done, a and b are two separate variables. Changing b.x leaves a.x untouched. This is one of the two ideas the lesson hinges on.
3
Skim the In-Class section below
You will see one interactive widget: the struct walkthrough. No need to use it yet; just know it is there.
4. Lesson Materials and Overview

Block 3 is about building the tools for serious programs. Today is the foundational tool: a way to design your own types. Up to now you have used the types the language gave you (int, double, char, pointers, arrays). Starting today, you describe the data your program needs and the compiler treats your description as a real type. Lesson 19 takes the same struct and points at it; Lesson 20 organizes structs across files. Today is the rock at the base.

Jump to
Slides Why structs Defining a struct Declaring and accessing Initializers enum typedef Struct copy

Slides

The Lesson 18 deck covers why structs exist, the syntax of defining and using them, enum and typedef, and the struct copy semantic. The slides are the spine of the lecture; the struct walkthrough is where you practice each idea hands-on.

Open Lesson 18 slides →

Why structs

You already know how to pass several related values around: a function takes three ints and a double. That works for small programs, but it scales badly. When the program grows, the same group of values appears in many places, and the meaning of each parameter has to be remembered from the function name alone. A struct lets you name the group once and treat it as a single value from then on.

In Python you used dictionaries and class instances for this. C has nothing as flexible as a dictionary, but it does give you the next best thing: a type you define yourself, with named fields and known sizes. The compiler reserves a single block of memory for the whole group and lets you reach into it by name.

Defining a struct

A struct definition introduces a new type. The type has a tag (the name after the word struct) and a list of fields inside braces. Each field has its own type and its own name. End the definition with a closing brace and a semicolon.

struct Pokemon {
  int pokedex_num;
  int hp;
  int attack;
  int defense;
  double catch_rate;
};

This does not allocate any memory yet. It declares a type, the same way int is a type. You can declare as many variables of this type as you want, or none. Field names are local to the struct: another struct can have its own field called hp with no conflict.

Declaring and accessing

To make a variable of a struct type, write the whole type name (including the word struct) followed by the variable name. To read or write a field, use the dot operator.

struct Pokemon pikachu;
pikachu.pokedex_num = 25;
pikachu.hp = 35;
printf("hp: %d\n", pikachu.hp);

The dot operator picks one field out of the bundle. pikachu.hp reads as "the hp field of the pikachu variable". The same syntax works for assignment and for reading. Heads up: declaring a struct without an initializer leaves all its fields uninitialized, exactly like an uninitialized primitive from Lesson 2.

Initializers: positional and designated

You can set all fields in one statement at declaration time. Two forms:

// positional: values in field-declaration order
struct Pokemon pikachu = { 25, 35, 55, 40, 0.255 };

// designated: explicit field names, any order, skip-allowed
struct Pokemon charmander = {
  .pokedex_num = 4,
  .hp = 39,
  .attack = 52,
};

Prefer designated initializers in your own code. They survive field reorderings, they let you skip fields you do not care about (skipped fields are zero-initialized), and a reader can see the field name at the call site instead of counting commas.

enum: names for a set of related integers

An enum is a list of named integer constants. The compiler hands out values starting from 0 unless you say otherwise. Enums pair naturally with structs: a struct field has a known set of allowed values, and the enum members are the readable names for them.

enum PokemonType { TYPE_FIRE, TYPE_WATER, TYPE_GRASS, TYPE_ELECTRIC, TYPE_PSYCHIC, TYPE_NORMAL };

// TYPE_FIRE is 0, TYPE_WATER is 1, ... TYPE_NORMAL is 5.
enum PokemonType t = TYPE_ELECTRIC;  // t holds the integer 3

Style note: write the member names in SCREAMING_SNAKE_CASE. They live in the same namespace as ordinary names; the all-caps convention signals "this is a constant".

typedef: a shorter alias for an existing type

Writing struct Pokemon everywhere gets old fast. typedef lets you give an existing type a second name and use that second name interchangeably.

// after the struct Pokemon definition above
typedef struct Pokemon pokemon_t;

pokemon_t pikachu;  // same thing as struct Pokemon pikachu

Style note: typedef names use the _t suffix. The standard library follows this rule (size_t, time_t, pid_t) and matching it makes your code look like it belongs in the language.

Real-world C code typedef-s almost every struct so that the word struct rarely appears outside the type definitions themselves.

DFCS C Programming Standard. Both readability tools you just learned are formalized in the course style guide. §5.3 requires typedef names to use snake_case with a _t suffix (so pokemon_t, not PokemonType or pokemon). §5.5 requires enum constants to use SCREAMING_SNAKE_CASE (so TYPE_FIRE, not type_fire or Fire). The full standard lives in the course Resources section; both rules apply to Lab 18 and every C lab after this one.

Struct copy: assignment copies the whole value

This is the surprise of Lesson 18 and the bridge to Lesson 19. When you write b = a; for two struct variables of the same type, C copies every field of a into the corresponding field of b. The two variables are now equal but they are SEPARATE: changing one does not affect the other.

pokemon_t a = { .hp = 39 };
pokemon_t b = a;  // copy every field
b.hp = 100;
printf("%d %d\n", a.hp, b.hp);  // prints 39 100

This is the opposite of what Python does with object assignment. In Python, b = a would point both names at the same object; changing one would visibly change the other. In C, structs are values, and values get copied. Tomorrow in Lesson 19 we will see what this means when you pass a struct to a function as an argument and why C programmers usually pass a pointer to a struct instead of the whole thing.

5. In-Class Work

Three things to do in class. Use the checklist to track your progress.

  • Work through the struct walkthrough below. Twelve guided tasks covering struct definition, dot access, designated initializers, enum, typedef, and the struct copy semantic. About 25 minutes.
  • Complete Lab 18: Pokemon. Design and use a struct Pokemon and a related enum. Auto-graded through GitHub Classroom. Full instructions in the lab repo.
  • Receive the PEX2 assignment. Individual project covering structs (today) and file I/O (Lesson 21). Spans Lessons 18 through 26 with the final submission due Lesson 26. Read the handout this week and start planning your struct design now.

struct Walkthrough

Twelve tasks across five sections. Define a struct Pokemon, declare variables of it, set fields, use designated initializers, alias the type with typedef, then watch what happens when you copy one struct into another.

Before you begin

Enter your name. It will appear on the completion screen so you can include it in your screenshot for the Lesson 18 reflection.

CS210 Lesson 18 · struct Walkthrough

Build a Pokemon type in C. Define a struct, declare variables of it, set fields, use enums, give types shorter names with typedef, and watch what happens when you copy a struct. Type each statement at the prompt.
Task 0 of 12
Section 1: Defining your first struct
Current task
Loading...
Types defined
No types yet. Define a struct on the left.
Variables
No variables yet.
struct>
How this works: This is not a Linux terminal. It is a teaching tool that simulates what C struct definitions and field accesses do. The task card tells you what to type next; only the expected command advances the walkthrough so the state stays predictable. Mistype twice and the hint button will pulse. After the walkthrough completes, free mode unlocks so you can experiment.
6. After Class
  • Finish Lab 18 if you did not complete it in class. Submit through GitHub Classroom before Lesson 19.
  • Submit the Lesson 18 reflection in Blackboard. Enter your completion code and answer the reflection prompt.
  • Read the PEX2 handout this week. Eight lessons from today, individual work, structs and file I/O. Start sketching your struct design now even though file I/O lands at Lesson 21.
  • Read Beej-C Chapter 8 cont. and Chapter 20 (Structs II) for Lesson 19.
  • Replay the walkthrough in free mode. Define your own struct of something you care about (a class roster entry, a song, a stat block) and see if you can predict what each field will show in the Variables pane.
  • Heads up: Quiz 7 at Lesson 20 covers structs (Lessons 18 and 19).
Need help? Check the course Resources section first (DFCS C Programming Standard, Git troubleshooting, course tooling). If you are still stuck, schedule EI with your instructor. Bring specific code or specific widget screenshots, and the exact error message or output you do not understand. Specific questions get unstuck quickly.