0
0
CHow-ToBeginner · 3 min read

How to Use Arrow Operator in C: Syntax and Examples

In C, the -> operator is used to access members of a struct through a pointer to that struct. It combines dereferencing the pointer and accessing the member in one step, like pointer->member.
📐

Syntax

The arrow operator syntax is pointer->member, where pointer is a pointer to a struct, and member is a field inside that struct. It is a shortcut for (*pointer).member.

  • pointer: a pointer variable pointing to a struct
  • ->: arrow operator to access struct member via pointer
  • member: the field inside the struct to access
c
struct Point {
    int x;
    int y;
};

struct Point *p;

// Access member x using arrow operator
p->x = 10;
💻

Example

This example shows how to create a struct, use a pointer to it, and access its members using the arrow operator.

c
#include <stdio.h>

struct Point {
    int x;
    int y;
};

int main() {
    struct Point pt = {5, 10};
    struct Point *p = &pt;

    // Access members using arrow operator
    printf("x = %d, y = %d\n", p->x, p->y);

    // Modify members using arrow operator
    p->x = 20;
    p->y = 40;

    printf("After modification: x = %d, y = %d\n", p->x, p->y);

    return 0;
}
Output
x = 5, y = 10 After modification: x = 20, y = 40
⚠️

Common Pitfalls

Common mistakes when using the arrow operator include:

  • Using -> on a struct variable instead of a pointer (should use dot . operator instead).
  • Dereferencing a NULL pointer before using ->, which causes a crash.
  • Confusing (*pointer).member and pointer->member (they are equivalent, but the arrow is simpler).
c
#include <stdio.h>

struct Point {
    int x;
    int y;
};

int main() {
    struct Point pt = {1, 2};
    struct Point *p = &pt;

    // Wrong: using arrow on struct variable (not pointer)
    // printf("x = %d\n", pt->x); // ERROR

    // Correct: use dot operator on struct variable
    printf("x = %d\n", pt.x);

    // Correct: use arrow operator on pointer
    printf("y = %d\n", p->y);

    return 0;
}
Output
x = 1 y = 2
📊

Quick Reference

Use the arrow operator -> when you have a pointer to a struct and want to access its members. Use the dot operator . when you have the struct variable itself.

  • pointer->member is the same as (*pointer).member
  • Do not use -> on non-pointer struct variables
  • Always ensure the pointer is not NULL before using ->

Key Takeaways

Use the arrow operator (->) to access struct members through a pointer in C.
The arrow operator is shorthand for dereferencing a pointer and accessing a member: (*pointer).member.
Do not use -> on struct variables; use the dot operator (.) instead.
Always ensure the pointer is valid (not NULL) before using the arrow operator.
Using -> simplifies code and improves readability when working with struct pointers.