Typedef and Struct Pointers

Typedef and Struct Pointers in C: does not create a type. It creates a nickname for a type that already exists.

The Analogy: A Nickname, Not a New Person

typedef does not create a type. It creates a nickname for a type that already exists. "The 09:15 to Bristol" and "the commuter train" are two names for one train — call it either and the same train arrives.

This is the single most important thing to understand about typedef, because it sets the limits of what it can do for you. Writing typedef int Metres; and typedef int Seconds; does not stop you assigning one to the other; both names mean int, and the compiler sees no difference at all. A nickname improves reading, not checking.

What it buys is real, though. It removes the struct keyword from every use site. It gives self-referential and function-pointer types a name you can say out loud. And in its most valuable form, it lets a header say "there is a type called Stack and you may hold pointers to it" without revealing a single one of its fields — which is how you build a module whose internals can change without recompiling its callers.


Syntax or Core Structure

#include <stdio.h>

/* An anonymous struct with the alias Account. */
typedef struct {
    char   name[32];
    int    id;
    double balance;
} Account;

/* Tagged, because the struct has to refer to itself. */
typedef struct Node {
    int          value;
    struct Node *next;
} Node;

typedef unsigned long ticks_t;

int main(void) {
    Account a = { .id = 7001, .balance = 250.75 };
    snprintf(a.name, sizeof a.name, "%s", "Grace Hopper");

    Account *p = &a;                   /* no "struct" keyword needed */
    printf("%s (%d) balance %.2f\n", p->name, p->id, p->balance);

    Node third  = { 3, NULL };
    Node second = { 2, &third };
    Node first  = { 1, &second };

    for (const Node *it = &first; it != NULL; it = it->next)
        printf("%d%s", it->value, it->next ? " -> " : "\n");

    ticks_t elapsed = 1500;
    printf("elapsed %lu ticks\n", elapsed);
    return 0;
}

Output:

Grace Hopper (7001) balance 250.75
1 -> 2 -> 3
elapsed 1500 ticks

That loop is a linked list traversal, and it is the reason self-referential structs matter: it = it->next walks a chain whose length was never declared anywhere.

Why the tag is required for self-reference

/* Broken: the alias Node does not exist yet inside the braces. */
typedef struct {
    Node *next;                    /* error: unknown type name */
} Node;

/* Works: the tag "struct Node" is usable as soon as it is written. */
typedef struct Node {
    struct Node *next;
} Node;

/* Also works, and is often clearer: name it first, define it after. */
typedef struct Node Node;
struct Node {
    int   value;
    Node *next;                    /* the alias is available now */
};

The alias only comes into existence at the closing semicolon. The tag exists from the moment it is written, so anything that needs to name itself needs a tag. Using the same word for both — struct Node and Node — is legal, conventional, and what most codebases do; they live in separate namespaces, so there is no conflict.


Technical Depth: What an Alias Can and Cannot Do

FormWhat it namesNotes
typedef struct { ... } T;an unnamed structcannot refer to itself, cannot be forward-declared
typedef struct Tag { ... } T;struct Tagthe usual choice; self-reference works
typedef struct Tag T;struct Tag, not yet definedT * is legal, T by value is not
typedef unsigned long ticks_t;unsigned longinterchangeable with unsigned long everywhere
typedef int Grid[3][4];a 3x4 array of inthides the array; parameters still decay
typedef int (*Cmp)(const void *, const void *);a function pointerthe main case where typedef is near-essential

No new type means no new checking

typedef int Metres;
typedef int Seconds;

Metres  distance = 100;
Seconds duration = 9;

duration = distance;        /* compiles silently: both are int */

If you want the compiler to catch that, wrap each in a one-field struct — a distinct struct is a distinct type, and assigning one to the other is an error. That is the whole trick behind "strongly typed units" in C.

The opaque handle: the pattern worth learning

A header can name a type it never defines. Callers may then hold and pass Stack * while knowing nothing about the fields:

/* stack.h — what the caller sees */
typedef struct Stack Stack;      /* incomplete type: no body here */

Stack *stack_create(size_t capacity);
void   stack_destroy(Stack *s);
/* stack.c — the only file that knows the layout */
struct Stack {
    int   *data;
    size_t count;
    size_t capacity;
};

Because the caller's compiler never sees the body, it cannot compute sizeof(Stack) and cannot write s->count. Both attempts are compile errors, not conventions to be politely respected. The payoff: you can add a field, reorder them, or replace the array with a linked list, and every caller still compiles unchanged. This is exactly how FILE works — you have used FILE * for a whole track without ever knowing what is inside one.

The cost is that callers can no longer declare one on the stack, which is why opaque types almost always come with a create/destroy pair that allocates on the heap.

Function pointer aliases

#include <stdlib.h>

typedef int (*Cmp)(const void *, const void *);

static int by_int(const void *a, const void *b) {
    int x = *(const int *)a, y = *(const int *)b;
    return (x > y) - (x < y);          /* no overflow, unlike x - y */
}

void sort_ints(int *a, size_t n) {
    Cmp compare = by_int;              /* vs int (*compare)(const void*, const void*) */
    qsort(a, n, sizeof *a, compare);
}

Without the alias, a function that takes a comparator has a declaration most people cannot read at a glance. With it, the parameter is just Cmp compare. The (x > y) - (x < y) idiom is worth stealing too: subtracting the values can overflow for large ints, this cannot.

Why hiding a pointer in the alias backfires

typedef struct Session *SessionRef;    /* the star is now invisible */

void f(const SessionRef s);            /* what is const here? */

const SessionRef means "a constant pointer to a modifiable Session" — the pointer is protected and the data is not, the opposite of what most readers assume. A reader also cannot tell that s might be NULL, or that it needs freeing. Keep the star visible: typedef struct Session Session; and write Session * at every use site.


Real World Example: A Stack Module Nobody Can Peek Inside

Three files. The header is the contract, the .c file is the secret, and main.c is a caller that could not break the invariants even if it tried.

/* ---------- stack.h ---------- */
#ifndef STACK_H
#define STACK_H

#include <stddef.h>

typedef struct Stack Stack;

/* Returns NULL on bad capacity or out of memory.
   Every successful stack_create must be paired with one stack_destroy. */
Stack *stack_create(size_t capacity);
void   stack_destroy(Stack *s);

int    stack_push(Stack *s, int value);      /* 0 ok, -1 full */
int    stack_pop(Stack *s, int *out);        /* 0 ok, -1 empty */
size_t stack_size(const Stack *s);

#endif
/* ---------- stack.c ---------- */
#include "stack.h"
#include <stdlib.h>

struct Stack {
    int   *data;
    size_t count;
    size_t capacity;
};

Stack *stack_create(size_t capacity) {
    if (capacity == 0) return NULL;

    Stack *s = malloc(sizeof *s);
    if (s == NULL) return NULL;

    s->data = malloc(capacity * sizeof *s->data);
    if (s->data == NULL) { free(s); return NULL; }

    s->count = 0;
    s->capacity = capacity;
    return s;
}

void stack_destroy(Stack *s) {
    if (s == NULL) return;              /* mirrors free(NULL) being legal */
    free(s->data);
    free(s);
}

int stack_push(Stack *s, int value) {
    if (s == NULL || s->count == s->capacity) return -1;
    s->data[s->count++] = value;
    return 0;
}

int stack_pop(Stack *s, int *out) {
    if (s == NULL || s->count == 0) return -1;
    s->count--;
    if (out != NULL) *out = s->data[s->count];
    return 0;
}

size_t stack_size(const Stack *s) {
    return (s == NULL) ? 0 : s->count;
}
/* ---------- main.c ---------- */
#include <stdio.h>
#include "stack.h"

int main(void) {
    Stack *s = stack_create(4);
    if (s == NULL) { fprintf(stderr, "out of memory\n"); return 1; }

    for (int i = 1; i <= 5; i++)
        printf("push %d -> %s\n", i, stack_push(s, i) == 0 ? "ok" : "full");

    printf("size %zu\n", stack_size(s));

    int value;
    while (stack_pop(s, &value) == 0)
        printf("pop %d\n", value);

    stack_destroy(s);
    return 0;
}

Build it as two translation units:

gcc -std=c17 -Wall -Wextra -fsanitize=address -o app main.c stack.c

Output:

push 1 -> ok
push 2 -> ok
push 3 -> ok
push 4 -> ok
push 5 -> full
size 4
pop 4
pop 3
pop 2
pop 1

The fifth push is refused rather than overrunning the buffer, and the pops come back in reverse order because a stack is last-in-first-out.

Four decisions carry this design:

  1. The handle is opaque. main.c cannot write s->count = 99, so the invariant count <= capacity is enforced by the compiler, not by trust.
  2. stack_pop takes an out-parameter. Returning the value directly would leave no room for an error code, since any int is a legal stack entry. This is the same shape as parse_int from the pointers lesson.
  3. The failure path in stack_create cleans up after itself. If the second malloc fails, the first block is freed before returning NULL — otherwise a rejected create would still leak.
  4. stack_destroy(NULL) is a no-op. Callers can free unconditionally, exactly as they already do with free.

Note what the caller must not do: free(s) instead of stack_destroy(s). That would release the handle and leak s->data, and the compiler cannot warn about it because free accepts any void *. The header comment saying so is the only defence, which is why every create in a real codebase documents its matching destroy.


Common Mistakes

  1. Expecting an alias to catch a mix-up. typedef int Metres; and typedef int Seconds; are the same type; assigning one to the other is silent and correct as far as the compiler is concerned. Use a one-field struct when you actually want the error.
  2. Self-referencing an anonymous struct. typedef struct { Node *next; } Node; fails, because Node does not exist until the closing semicolon. Give the struct a tag and use struct Node *next;.
  3. Declaring an opaque type by value. With only typedef struct Stack Stack; in scope, Stack s; is an error ("incomplete type") and so is sizeof(Stack). Hold Stack * and get it from the module's create function.
  4. Hiding the star. typedef struct Session *SessionRef; makes const SessionRef mean a const pointer, not const data, and hides from the reader that the value can be NULL and probably owns memory.
  5. Freeing a handle with free instead of the module's destroy. free(s) releases the struct and leaks everything it pointed to. No warning will be issued; only the header's documented pairing prevents it.
  6. typedefing an array and forgetting it is still an array. With typedef int Row[4];, a parameter Row r silently becomes int *r and sizeof r is the pointer size — the same decay as always, only now invisible.
  7. Leaving off the alias name. typedef struct { int x; }; declares nothing usable; some compilers only warn. Every typedef must end in the new name before the semicolon.
  8. Aliasing every primitive. A file full of typedef int i32; typedef char byte; forces readers to look up each name. Prefer the standard spellings — size_t, int32_t, uint8_t from <stdint.h> — and note that names ending in _t are formally reserved for the implementation, so your own aliases are safest without that suffix.

Best Practices

  • typedef your structs, and give them a tag as well; the tag costs one word and unlocks self-reference and forward declaration.
  • Reuse the same word for tag and alias (typedef struct Item { ... } Item;). It is idiomatic and they cannot collide.
  • Keep pointers visible at the use site. Alias the struct, never the pointer to it.
  • Expose an opaque typedef struct X X; in headers whenever callers have no business seeing the fields — it turns a convention into a compile error.
  • Pair every create with exactly one destroy, make destroy(NULL) a no-op, and say so in the header comment.
  • Use typedef for function pointer types. It is the one case where the alias is genuinely easier to read than the thing it names.
  • Prefer the standard library's aliases (size_t, ptrdiff_t, uint32_t, time_t) over inventing your own for the same purpose.
  • When you want distinct types rather than distinct names, wrap the value in a struct — that is the only construct in C that creates a genuinely new type.

Practice Exercises

  1. Prove the alias is not a type. Write a program with typedef int Metres; and typedef int Seconds;, assign one variable to the other, and confirm that gcc -Wall -Wextra -Wconversion says nothing. Then redefine both as one-field structs, try the same assignment, and record the exact error text. Add a metres_add function to show what the struct version costs you in convenience.
  2. Build a linked list. Using typedef struct Node Node; followed by the struct definition, write Node *list_push_front(Node *head, int value), void list_print(const Node *head) and void list_free(Node *head). Push 1 through 5, print the list, free it, and confirm -fsanitize=address reports no leaks. Explain why list_push_front returns the new head instead of taking Node *head.
  3. Break the encapsulation on purpose. Take the Stack module from this lesson and, in main.c, try Stack s;, sizeof(Stack) and s->count. Write down each error message. Then move struct Stack { ... } from stack.c into stack.h, confirm all three now compile, and describe in two sentences what you have lost.
  4. A comparator you can swap. Add typedef int (*Cmp)(const void *, const void *); and a sort_with(int *a, size_t n, Cmp compare) wrapper around qsort. Supply an ascending and a descending comparator, sort {4, -2, 7, 0, -9, 3, 8} both ways, and print the results. Then write the same sort_with declaration without the typedef and compare how the two read.