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

Modifying struct members via pointers

Modifying struct members via pointers

What you'll learn: How to use the arrow operator (->) to access and change data inside a structure when you only have its memory address.

The remote control analogy

Imagine a struct is a physical television set. If you are standing right in front of it, you can press the buttons on the frame to change the channel. In C, this is like using the dot operator (tv.channel = 5).

However, if you are sitting on the couch, you aren't touching the TV; you are holding a "remote control" that points to the TV. To change the channel from a distance, you need a way to tell C: "Go to the address this pointer is holding, find the structure there, and change one of its members."

Meet the Arrow Operator (->)

In C, when you have a pointer to a struct, you use the arrow operator (->) to reach inside. It is a combination of a dash and a greater-than sign.

You might wonder why we don't just use *ptr.member. The problem is that in C, the dot operator has higher priority than the asterisk. C would try to find a member inside the pointer itself (which doesn't exist) rather than the struct the pointer is looking at. While you could write (*ptr).member, it is clunky and hard to read. The arrow operator was created as a shorthand to make your code much cleaner.

Code Example: The Player Update

In this example, we pass a pointer to a function so we can modify the original player's score without making a copy of the whole structure.

#include <stdio.h>

struct Player {
    char name[50];
    int score;
};

void addPoints(struct Player *p, int points) {
    // We use -> because 'p' is a pointer (the remote)
    // This changes the actual variable back in main
    p->score += points;
}

int main() {
    struct Player hero = {"Alice", 100};
    struct Player *ptr = &hero;

    // Accessing data via pointer
    printf("%s has %d points.\n", ptr->name, ptr->score);

    // Modifying data via pointer
    addPoints(&hero, 50);

    printf("New score: %d\n", hero.score);
    return 0;
}

Why this matters

Passing pointers to structs is the "pro" way to write C. Instead of your computer laboriously copying a large struct every time you pass it to a function, you simply pass a tiny memory address. The arrow operator gives you the power to manipulate that distant data efficiently.

Key takeaway

Use the dot operator (.) for direct struct variables and the arrow operator (->) for pointers to structs.