Chapter 3 — Structs
`struct` groups related fields under one name. With `typedef` you get a clean alias. The building block of every C data model.
What you'll learn
- 1Define a `struct` and access its fields.
- 2Use `typedef` for a clean type name.
- 3Allocate arrays of structs.
- 4Use struct pointers with `->`.
Core Concepts
1) Define and use
struct Point {
int x;
int y;
};
struct Point p = {3, 4};
printf("%d %d\n", p.x, p.y);2) `typedef`
typedef struct {
int x;
int y;
} Point;
Point p = {3, 4}; // no more "struct" needed3) Array of structs
Point pts[3] = { {0,0}, {1,1}, {2,4} };
for (int i = 0; i < 3; i++) {
printf("(%d, %d)\n", pts[i].x, pts[i].y);
}4) Pointer to struct → `->`
Point p = {1, 2};
Point *pp = &p;
printf("%d\n", pp->x); // same as (*pp).x`->` is just sugar for `(*p).field`.
5) Passing structs
Passing by value copies all fields — fine for small structs, expensive for large ones. Pass by pointer when the struct is big or you want to modify it.
Examples
Example 1 — `ex01_basic.c`: define + access
struct Point { int x, y; };
struct Point p = {3, 4};
printf("x=%d y=%d\n", p.x, p.y);**Output**
x=3 y=4Key: dot operator (`.`) reads/writes fields on a struct value.
Example 2 — `ex02_typedef.c`: cleaner with typedef
typedef struct {
char name[32];
int age;
} Person;
Person p = {"Alice", 30};
printf("%s, %d\n", p.name, p.age);**Output**
Alice, 30Key: typedef gives you a type name without writing `struct` every time.
Example 3 — `ex03_struct_array.c`: list of points
Point pts[3] = { {0,0}, {1,1}, {2,4} };
for (int i = 0; i < 3; i++) {
printf("(%d, %d)\n", pts[i].x, pts[i].y);
}**Output**
(0, 0)
(1, 1)
(2, 4)Key: arrays of structs are stored contiguously.
Example 4 — `ex04_pointer.c`: pointer + `->`
Person p = {"Bob", 25};
Person *pp = &p;
printf("%s is %d\n", pp->name, pp->age);
pp->age = 26;
printf("%d\n", p.age);**Output**
Bob is 25
26Key: `pp->age` mutates the original through the pointer.
Common mistakes
- **Confusing `.` and `->`** — `.` for value, `->` for pointer.
- **Forgetting `typedef`** then writing `struct X` everywhere.
- **Returning a stack struct** — fine if small; rarely a problem in practice.
- **Bitwise compare** — can't use `memcmp` reliably; padding bytes are unspecified.
Recap
- Group related fields with `struct`; `typedef` for ergonomics.
- `.` on values, `->` on pointers.
- Pass big structs by pointer.
Try it
cd src
gcc -std=c11 -Wall -o ex01 ex01_basic.c && ./ex01
gcc -std=c11 -Wall -o ex02 ex02_typedef.c && ./ex02
gcc -std=c11 -Wall -o ex03 ex03_struct_array.c && ./ex03
gcc -std=c11 -Wall -o ex04 ex04_pointer.c && ./ex04💻 Examples
Compilable, runnable examples — see the output yourself.
#include <stdio.h>
struct Point {
int x;
int y;
};
int main(void) {
struct Point p1 = {3, 4};
struct Point p2 = {.x = 1, .y = 2};
printf("p1 = (%d, %d)\n", p1.x, p1.y);
printf("p2 = (%d, %d)\n", p2.x, p2.y);
p1.x = 10;
printf("p1.x = (%d, %d)\n", p1.x, p1.y);
return 0;
}
x=3 y=4#include <stdio.h>
#include <math.h>
typedef struct {
double x;
double y;
} Point;
double distance(Point a, Point b) {
double dx = a.x - b.x;
double dy = a.y - b.y;
return sqrt(dx * dx + dy * dy);
}
int main(void) {
Point p = {0, 0};
Point q = {3, 4};
printf(": %.2f\n", distance(p, q)); /* 5.00 */
return 0;
}
Alice, 30#include <stdio.h>
typedef struct {
char name[32];
int score;
} Student;
int main(void) {
Student class_[] = {
{"Kim", 90},
{"Lee", 85},
{"Park", 78},
{"Choi", 92},
};
int n = (int)(sizeof(class_) / sizeof(class_[0]));
int sum = 0;
for (int i = 0; i < n; i++) {
printf("%-6s : %d\n", class_[i].name, class_[i].score);
sum += class_[i].score;
}
printf("mean: %.2f\n", (double)sum / n);
return 0;
}
(0, 0)
(1, 1)
(2, 4)#include <stdio.h>
typedef struct {
char name[32];
int age;
} Person;
void birthday(Person *p) {
p->age += 1; /* */
}
int main(void) {
Person p = {"", 20};
printf(" : %s, %d\n", p.name, p.age);
birthday(&p);
printf(" : %s, %d\n", p.name, p.age);
return 0;
}
Bob is 25
26📝 Exercises
Try them yourself first, then open the solution to compare.
Problem 1 (hw01.c)
Goal: Define `Point {x, y}`, write `double dist(Point a, Point b)` and demonstrate.
- Filename: hw01.c
▶Toggle solution
#include <stdio.h>
typedef struct {
double x;
double y;
} Vec2;
Vec2 add(Vec2 a, Vec2 b) {
Vec2 r = {a.x + b.x, a.y + b.y};
return r;
}
double dot(Vec2 a, Vec2 b) {
return a.x * b.x + a.y * b.y;
}
int main(void) {
Vec2 a = {1, 2}, b = {3, 4};
Vec2 c = add(a, b);
printf("a + b = (%.1f, %.1f)\n", c.x, c.y);
printf("a . b = %.1f\n", dot(a, b));
return 0;
}
Problem 2 (hw02.c)
Goal: Define `Student {name, score}`, store an array of 3, print mean score.
- Filename: hw02.c
▶Toggle solution
#include <stdio.h>
typedef struct {
char name[32];
int kor, eng, math;
} Student;
int main(void) {
Student arr[5] = {
{"Kim", 90, 85, 92},
{"Lee", 78, 88, 70},
{"Park", 95, 91, 89},
{"Choi", 60, 70, 65},
{"Han", 88, 76, 82},
};
int top_idx = 0;
double top_avg = 0;
for (int i = 0; i < 5; i++) {
double avg = (arr[i].kor + arr[i].eng + arr[i].math) / 3.0;
printf("%-6s mean %.2f\n", arr[i].name, avg);
if (avg > top_avg) { top_avg = avg; top_idx = i; }
}
printf("\nbest mean: %s (%.2f)\n", arr[top_idx].name, top_avg);
return 0;
}
Problem 3 (hw03.c)
Goal: Define `Book {title, author, price}` and print one book's info.
- Filename: hw03.c
▶Toggle solution
#include <stdio.h>
typedef struct {
int w;
int h;
} Rect;
int area(const Rect *r) { return r->w * r->h; }
int perimeter(const Rect *r) { return 2 * (r->w + r->h); }
int main(void) {
Rect r = {5, 3};
printf("area: %d\n", area(&r));
printf("perimeter: %d\n", perimeter(&r));
return 0;
}
All lecture materials and example code are openly available on GitHub.
View on GitHub ↗