Erik Fredericks, frederer@gvsu.edu Fall 2025
Based on material provided by Erin Carrier, Austin Ferguson, and Katherine Bowers
We can structure our data
Structs allow us to group together pieces of data
typedef struct Coord { double x; double y; } Coord;
We can treat Coord like a new type!
Coord
To create and use an instance of a struct:
Coord c; c.x = 5.0; c.y = 10;
Structs can container raw data types, pointers, arrays, even other structs!
We can access members of a struct with .
c.x = 5;
double d = c.y;
Structs still work with pointers!
We can create a pointer to a struct:
Coord* p = &c;
We can access members with ->
->
p->x = 1.0;
This is the same as (*p).x = 1.0;
(*p).x = 1.0;
We can allocate structs on the stack or the heap!
Methods! (member functions)
C does not support methods by default.
typedef struct Coord { double x; double y; } Coord; ... Coord c;
Also can do:
struct Coord2 { double x; double y; } ... struct Coord2 d;
typedef defines a new type!
typedef type name;
This is not limited to structs:
typedef int* int_pointer; int x = 40; int_pointer p = &x; printf("p: %p, *p: %d\n", p, *p);
With structs, this prevents us from typing struct Coord over and over again!
struct Coord
l
r
#include <stdio.h> #include <stdlib.h> #include <stdbool.h> typedef struct Player { } Player; void setupPlayer(?) { } int main() { return 0; }
typedef struct Player { int roomID; int health; char* name; } Player;
void setupPlayer(Player* p) { p->roomID = 0; p->health = 10; p->name = "Erik"; }
int main() { // create and setup player Player player; setupPlayer(&player); bool done = false; // forever loop variable char ch; // user input // forever loop while (!done) { } printf("Done.\n"); return 0; }
// forever loop while (!done) { printf("---\n"); printf("%d %d %s\n", player.roomID, player.health, player.name); printf("Waiting for input [l, r, q]: "); // read a character - NOTE THE SPACE int res = scanf(" %c", &ch); if(res == EOF) done = true; // Ctrl+D pressed else { if (ch == 'l') player.roomID--; else if (ch == 'r') player.roomID++; else if (ch == 'q') done = true; } printf("---\n\n"); }
combining type definition with naming
Player* p;
extensions: make the rooms bounded add description to each room create a struct for a room