Skip to content
Tutorials Center
My learning

Topics

Lesson 58 of 135 ยท Structures and Unions

Structures and Pointers

Learn how C structures and pointers work together - the -> operator, passing structs by pointer, const struct parameters, heap-allocated structs and self-referential structs.

In Structures you passed and returned structs by value, which copies every member. That's fine for a small point or a few statistics, but most real structs are larger, need to be modified by the functions that receive them, or must live longer than the function that creates them. In all three cases you work with a pointer to the struct instead.

Pointers and structs together are the backbone of C programming. File handles (FILE *), linked lists, trees, hash tables and nearly every library API you'll ever use are built from them. This lesson covers the arrow operator, passing structs by pointer with and without const, creating structs on the heap with clear ownership, structs that own memory, and self-referential structs that point to other structs of the same type.

Pointers to structs and the arrow operator

A pointer to a struct works like any pointer: & takes the address, and * gets back to the struct. To reach a member through the pointer, you could write (*p).member. The parentheses are required because . binds more tightly than *; *p.member would mean *(p.member), which is a different thing entirely.

Since this pattern is everywhere, C has a shorthand: the arrow operator p->member means exactly (*p).member.

C Dot, star and arrow

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

All three increments change the same struct, so it prints clicks = 3. The rule is easy: use . when you have a struct, -> when you have a pointer to one. Chains like order->customer->address.city read naturally from left to right: follow two pointers, then pick a member of the embedded address struct.

Passing structs by pointer

Passing a pointer gives a function access to the caller's struct itself instead of a copy. That serves two different purposes, and const tells readers which one you mean:

  • To modify the caller's struct, take a plain pointer: void account_deposit(struct account *acct, long cents).
  • To read a large struct cheaply, take a pointer to const: void account_print(const struct account *acct). Only an address (8 bytes on 64-bit systems) is passed, and the compiler rejects any attempt to modify the struct through it (see const and Pointers).
C Modifying and reading through pointers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The balance ends at $155.51 after 2 transactions; the refused withdrawal didn't count. The last line shows the cost difference: the struct is 48 bytes, the pointer 8. Money is stored in whole cents as an integer, a common practice that avoids floating-point rounding in sums.

Taking a pointer brings one new responsibility: the pointer could be NULL. Library-style functions often check (if (acct == NULL) return false;); internal helpers usually document that the argument must not be null instead.

Structs on the heap

When a struct must outlive the function that creates it, or when you don't know how many you'll need, allocate it with malloc. The sizeof *p idiom works perfectly: struct account *a = malloc(sizeof *a);.

C code typically wraps this in a pair of functions, a constructor that allocates and initializes, and a destructor that frees. Naming them *_create and *_destroy (or *_new and *_free) makes ownership visible at every call site:

C Create and destroy functions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Pay attention to the order inside student_destroy: the struct's name must be freed before the struct, because after free(s) reading s->name would be a use after free. The constructor also cleans up after itself: if the second allocation fails, it frees the first one before returning NULL, so a failure never leaks.

Making student_destroy(NULL) a no-op, just like free(NULL), simplifies error paths: cleanup code can call it on anything without checking first.

Deep copies of structs that own memory

As you saw in the last lesson, assigning a struct copies its pointers but not what they point to. With struct student, struct student copy = *top; would make copy.name and top->name point to the same string. Destroying one would leave the other with a dangling name, and destroying both would be a double free.

When a struct owns memory, give it a copy function that duplicates the owned data too:

C
struct student *student_clone(const struct student *original)
{
    return student_create(original->name, original->grade);
}

Because student_create already allocates its own copy of the name, cloning is a one-liner. The result is a deep copy that can be modified and destroyed independently.

Self-referential structs

A struct can't contain a member of its own type, but it can contain a pointer to its own type. Inside the definition, struct node is already declared (as an incomplete type), so struct node *next; is allowed. This tiny feature is the foundation of linked lists, trees and graphs.

C A chain of nodes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Each new node goes in front, so the chain prints 40 -> 30 -> 20 -> 10 -> NULL with a sum of 100, and list->next->value follows two links to reach 30. Freeing a chain needs care: you must read head->next before calling free(head), which is why free_all saves it in a temporary. The Linked Lists lesson builds a full list with insertion, deletion, searching and reversal on this foundation.

Two structs can also point to each other. Declare one tag ahead of time with a forward declaration, struct department;, and then each can hold a pointer to the other.

Opaque types: hiding a struct's members

Pointers to incomplete struct types lead to a powerful design technique. A header can declare a struct without defining it:

C
/* stack.h */
typedef struct stack Stack;            /* incomplete: members are secret */

Stack *stack_create(void);
bool stack_push(Stack *s, int value);
void stack_destroy(Stack *s);

Code that includes the header can hold Stack * pointers and call the functions, but it can't see or touch the members, or even create a Stack on the stack, because it doesn't know its size. Only stack.c contains the full struct stack { ... }; definition. This is how the standard library's FILE works in practice, and it's C's version of encapsulation: you can change the struct's internals without breaking any code that uses it. You'll organize code this way in Multi-File Programs.

Returning a struct versus returning a pointer

Both styles are common, and they suit different situations:

Return a struct by value Return a pointer to a heap struct
Small, self-contained values (points, colors, results) Large structs, or structs that own resources
No allocation, nothing to free Caller must call the destroy function
Each copy is independent One shared object, passed around by pointer
Can't signal failure with NULL NULL naturally signals failure

What you must never do is return a pointer to a local struct:

C
struct point *broken(void)
{
    struct point p = {1, 2};
    return &p;      /* p dies when the function returns: dangling pointer */
}

GCC warns function returns address of local variable [-Wreturn-local-addr]. Return the struct by value, or allocate it on the heap.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Given struct item *p, which expression is equivalent to p->price?

    The arrow operator is shorthand for dereference-then-dot. *p.price would parse as *(p.price), because . binds more tightly than *.
  2. 2. A function only prints a large struct. Which parameter type is the best choice?

    A const pointer avoids copying the whole struct and lets the compiler reject accidental modifications.
  3. 3. In a destroy function for struct student { char *name; int grade; }, why must free(s->name) come before free(s)?

    Once the struct is freed, its members can no longer be read. free never follows pointers inside a block.
  4. 4. struct node *a = ...; struct node b = *a; Both structs contain char *label pointing to heap memory. What happens if you free a->label and later print b.label?

    Struct assignment is a shallow copy. Both label pointers hold the same address, so freeing it through one leaves the other dangling.
  5. 5. Why can struct node contain struct node *next but not struct node next?

    Inside its own definition the struct type is incomplete, so its size is unknown. A pointer to it is complete and has a known size.

Summary

  • p->member is shorthand for (*p).member. Use . with a struct and -> with a pointer to a struct.
  • Pass a plain pointer when a function must modify the caller's struct, and a const pointer when it only reads a large struct.
  • Heap structs are created with malloc(sizeof *p) and usually wrapped in *_create / *_destroy functions that make ownership clear and clean up on failure.
  • Free owned members before the struct itself, and make destroy functions accept NULL.
  • Struct assignment is a shallow copy; structs that own memory need a deep-copy function.
  • A struct can hold pointers to its own type, which is the basis of linked lists and trees. Incomplete (opaque) struct types hide implementation details behind pointers.
  • Never return the address of a local struct.

Next: Arrays of Structures and Nested Structures, where you'll build tables of records, sort them with qsort and nest structs inside structs.