Arrow operator vs dot operator
What you'll learn: You'll understand when to use the arrow operator (->) instead of the dot operator (.) to access structure members.
The Dot vs. The Arrow
In C, a structure is like a backpack containing different items. To get something out of a backpack you are physically holding, you use the dot operator. However, if you are holding a map (a pointer) that tells you where a backpack is located across the room, you have to follow that map first. This "follow and open" action is what the arrow operator does.
Accessing by Value (The Dot)
When you have a regular structure variable, the computer knows exactly where the data is in memory. You use the . to reach inside.
struct Player {
int health;
};
struct Player hero;
hero.health = 100; // Direct access
Accessing by Pointer (The Arrow)
When you have a pointer to a structure, you don't have the "backpack" itself; you have its address. To change the health through a pointer, you could write (*ptr).health. This tells C to "go to the address, then find the health."
But that's clunky to type. C provides the arrow operator (->) as a shortcut. It combines dereferencing the pointer and accessing the member into one clean motion.
struct Player hero;
struct Player *ptr = &hero;
// These two lines do the exact same thing:
(*ptr).health = 80;
ptr->health = 80; // The "C way" to do it
How to remember
- Use the Dot when you have the Data itself.
- Use the Arrow when you have an Address.
If you try to use a dot on a pointer, your compiler will complain that you are trying to find a member inside a memory address (which is just a number), rather than inside the structure itself. The arrow "points" the way from the pointer to the actual data.
Key takeaway
Use the dot operator (.) for direct structure variables and the arrow operator (->) for pointers to structures.