The dot operator for member access
What you'll learn: How to use the dot operator (.) to reach inside a structure and work with its individual pieces of data.
Cracking the shell
In C, a struct is like a container—think of it as a bento box or a physical folder. While the struct itself has a name, you rarely want to move the whole box around without looking inside. To actually use the data tucked away in those compartments, you need a way to "reach in."
This is where the dot operator (.) comes in. It acts as a connector between the name of your structure variable and the specific member you want to talk to.
How it works
Imagine you have a structure representing a video game character. The character has a name, a health score, and a level. If you name your specific character variable hero, you can’t just say health = 100; because the computer won't know whose health you are talking about. You must use the dot: hero.health = 100;.
Think of the dot as the word "of." When you write hero.level, you are telling C: "Look at the level of hero."
#include <stdio.h>
struct Player {
int health;
int level;
};
int main() {
// Create an instance of the struct
struct Player hero;
// Use the dot operator to assign values
hero.health = 95;
hero.level = 5;
// Use the dot operator to retrieve values
printf("Hero Health: %d\n", hero.health);
printf("Hero Level: %d\n", hero.level);
return 0;
}
Why it matters
The dot operator is the bridge between organized data and functional code. Once you use the dot to access a member, that member behaves exactly like a normal variable of its type.
For example, hero.health is just an integer. You can add to it (hero.health += 10), subtract from it, or pass it into a function. The structure keeps your data grouped together logically, but the dot operator gives you the surgical precision to change only the parts you need while leaving the rest of the container untouched.
Key takeaway
Use the dot operator (variable.member) to access or modify specific pieces of data stored inside a structure.