Course contentsShow
← C
Lesson 615 of 1,2199. Structures and UnionsFree lesson

Declaring a pointer to a struct

Declaring a pointer to a struct

What you'll learn: How to create a variable that stores the memory address of a structure rather than the structure itself.

The Mailbox Analogy

Imagine you have a large gift box (a struct). Carrying this box around from room to room is tiring and takes up a lot of space. Instead of moving the box, you could simply write down the address of where the box is sitting on a small sticky note.

In C, a pointer to a struct is that sticky note. It doesn't hold the data (the gift); it holds the location (the memory address) where the data lives. This is incredibly efficient because no matter how large or complex your structure is, the pointer is always the same small size.

Syntax: The Asterisk and the Type

To declare a pointer to a struct, you use the struct keyword followed by the tag name, just like a regular declaration, but you add an asterisk (*) before the variable name.

struct Player {
    int health;
    int level;
};

// 1. Create a regular struct variable (The Box)
struct Player hero;

// 2. Create a pointer to a struct (The Sticky Note)
struct Player *ptr;

// 3. Store the address of the hero in the pointer
ptr = &hero;

In the code above, struct Player *ptr tells the compiler: "I am creating a variable named ptr that is designed to point to a memory location where a struct Player is stored."

Why bother with pointers?

You might wonder why we don't just use the struct directly. As your programs grow, you will often pass data to functions. If you pass a regular struct, C makes a complete copy of every single piece of data inside it. If your struct has 50 fields, that’s a lot of copying!

By using a pointer, you only pass the address. It’s the difference between giving someone a copy of a 500-page book and just giving them the library's address so they can go look at the book themselves.

Key takeaway

A pointer to a struct stores a memory address, allowing you to reference large amounts of data efficiently without copying it.