Course contentsShow
← C
Lesson 239 of 1,2193. Operators and ExpressionsFree lesson

Member access `.` and `->`

Member access . and ->

What you'll learn: How to reach inside a structure to access its data, whether you are holding the structure itself or just a map to where it lives.

In C, we use "structs" to bundle different variables together into one package. Think of a struct like a physical folder labeled Student. Inside that folder, you have separate sheets for a name, an age, and a grade. To get to that information, C provides two specific keys: the dot operator (.) and the arrow operator (->).

The Dot Operator (.)

The dot is used when you have the actual object in your hand. If you have a variable Student s1;, you are holding the physical folder. To read the age inside, you use s1.age.

Think of the dot as "belonging to." If you say s1.age = 20, you are telling C: "Go to the s1 folder and change the age that belongs to it."

The Arrow Operator (->)

The arrow is used when you have a pointer to a struct. A pointer isn't the folder itself; it is a scrap of paper with the address of the folder written on it.

In C, if you have a pointer ptr, you can’t just say ptr.age because a memory address doesn’t have an age—the folder sitting at that address does. You would normally have to "dereference" the pointer first ((*ptr).age), which is clunky to type. The arrow operator is a convenient shortcut that says: "Follow this address to the destination, then look inside."

Seeing it in action

Here is how they look side-by-side in code:

#include <stdio.h>

struct Player {
    int score;
};

int main() {
    struct Player p1;      // The actual object
    struct Player *ptr;    // A pointer (address)
    
    ptr = &p1;             // ptr now points to p1

    // Using the dot on the actual object
    p1.score = 100;

    // Using the arrow on the pointer to the object
    ptr->score = 200; 

    // Both now refer to the same value
    printf("Score is: %d", p1.score); 
    
    return 0;
}

When to use which?

Choosing between them is simple:

  • Use the dot if the variable is a standard struct type.
  • Use the arrow if the variable is a pointer (look for the * in the declaration).

Key takeaway

Use . to access members of a struct directly, and -> to access members when you are working through a pointer.