← Back to C series
🎯
Advanced
struct · typedef · pointer · array

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.

structtypedef
Duration
1-2 hours
Level
📊 Intermediate
Prerequisite
🎯 Advanced 2
Outcome
Group fields into clean domain types

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

c
struct Point {
    int x;
    int y;
};

struct Point p = {3, 4};
printf("%d %d\n", p.x, p.y);

2) `typedef`

c
typedef struct {
    int x;
    int y;
} Point;

Point p = {3, 4};   // no more "struct" needed

3) Array of structs

c
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 → `->`

c
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

c
struct Point { int x, y; };
struct Point p = {3, 4};
printf("x=%d y=%d\n", p.x, p.y);

**Output**

text
x=3 y=4

Key: dot operator (`.`) reads/writes fields on a struct value.

Example 2 — `ex02_typedef.c`: cleaner with typedef

c
typedef struct {
    char name[32];
    int age;
} Person;

Person p = {"Alice", 30};
printf("%s, %d\n", p.name, p.age);

**Output**

text
Alice, 30

Key: typedef gives you a type name without writing `struct` every time.

Example 3 — `ex03_struct_array.c`: list of points

c
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**

text
(0, 0)
(1, 1)
(2, 4)

Key: arrays of structs are stored contiguously.

Example 4 — `ex04_pointer.c`: pointer + `->`

c
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**

text
Bob is 25
26

Key: `pp->age` mutates the original through the pointer.

Common mistakes

  1. **Confusing `.` and `->`** — `.` for value, `->` for pointer.
  2. **Forgetting `typedef`** then writing `struct X` everywhere.
  3. **Returning a stack struct** — fine if small; rarely a problem in practice.
  4. **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

bash
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.

ex01_basic.cdefine + access
CODE
#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;
}
▶ Output
x=3 y=4
ex02_typedef.ccleaner with typedef
CODE
#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;
}
▶ Output
Alice, 30
ex03_struct_array.clist of points
CODE
#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;
}
▶ Output
(0, 0)
(1, 1)
(2, 4)
ex04_pointer.cpointer + `->`
CODE
#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;
}
▶ Output
Bob is 25
26

📝 Exercises

Try them yourself first, then open the solution to compare.

Exercise 1

Problem 1 (hw01.c)

Goal: Define `Point {x, y}`, write `double dist(Point a, Point b)` and demonstrate.

Requirements
  • Filename: hw01.c
Toggle solution
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;
}
Exercise 2

Problem 2 (hw02.c)

Goal: Define `Student {name, score}`, store an array of 3, print mean score.

Requirements
  • Filename: hw02.c
Toggle solution
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;
}
Exercise 3

Problem 3 (hw03.c)

Goal: Define `Book {title, author, price}` and print one book's info.

Requirements
  • Filename: hw03.c
Toggle solution
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;
}
Example code / lecture materials

All lecture materials and example code are openly available on GitHub.

View on GitHub ↗