Codiqo

Learn C · lesson 39 of 60 · about 8 minutes

typedef and Struct Pointers

Charge files to the user's quota: give types short names with typedef, and reach members through a pointer with ->.

What you'll learn

  • Name a type with typedef
  • Pass a struct pointer to a function
  • Use the -> operator

The quota

Every user gets a quota of 2000 KiB. The report reads the sizes of the files the user saves, until 0, and charges each one to the quota. Quota is a struct named with typedef, so it's written Quota instead of struct Quota. use_space(Quota *q, int kib) takes a pointer, so it changes the report's quota and not a copy, and reaches the members with q->used_kib. A file that doesn't fit, or a size that isn't above 0, is refused and the quota stays as it was.

Shorter names

typedef struct { ... } Player; defines the struct and names it Player, so you can write Player p; instead of struct Player p;. Most C code does this.

Pointers to structs

Passing a big struct to a function copies all of it, and changes are lost. Pass a pointer instead.

With a pointer Player *pp, you could write (*pp).level, but C has a neater arrow: pp->level.

Levelling up through a pointer

#include <stdio.h>

typedef struct {
    char name[16];
    int level;
    int xp;
} Player;

void gain_xp(Player *p, int amount) {
    p->xp += amount;
    while (p->xp >= 100) {
        p->xp -= 100;
        p->level++;
    }
}

int main(void) {
    Player phoebe = {"Phoebe", 1, 80};
    gain_xp(&phoebe, 150);
    printf("%s: level %d, %d XP\n", phoebe.name, phoebe.level, phoebe.xp);
    return 0;
}

Output

Phoebe: level 3, 30 XP

Tip

Use . with a struct variable and -> with a pointer to a struct. If the compiler complains, you've probably used the wrong one.

Read-only pointers

A function that only reads a struct can still take a pointer, to avoid copying it, and mark it const so it promises not to change it: int area(const Rect *r). Writing r->w = 0; inside would then be a compile error.

Reading through a const pointer

#include <stdio.h>

typedef struct {
    int w;
    int h;
} Rect;

int area(const Rect *r) {
    return r->w * r->h;
}

int main(void) {
    Rect room = {4, 3};
    printf("%d\n", area(&room));
    return 0;
}

Output

12

Now try it yourself

This lesson is free in Codiqo, with 8 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.