02. Pointers to Structs & The Arrow Operator (->)

🟡 Difficulty: Intermediate | Struct Address Manipulation, Arrow Shorthand & Zero-Copy In-Place Function Mutation

📖 Definition

A pointer to a struct stores the starting memory address of a structure instance in RAM. The arrow operator (->) is a syntactic shorthand in C used to access members of a struct directly through its pointer address: ptr->field is completely identical to dereferencing first and using the dot operator: (*ptr).field.

🎯 Why It Is Used

  • Zero-Copy Function Parameters: Passing an 8-byte pointer address to a large 500-byte struct avoids copying the entire struct onto the stack frame.
  • In-Place Member Mutation: Functions can modify struct fields in the caller's stack or heap memory directly.
  • Dynamic Data Structure Linking: Self-referential pointers inside structs (e.g. struct Node *next;) form the foundation of linked lists, trees, and graphs.

⚙️ How It Works: Operator Precedence

In C, the member selection dot operator (.) has higher precedence than the dereference operator (*). Writing *ptr.field is interpreted by the compiler as *(ptr.field), which triggers a syntax compilation error because ptr is a pointer, not a struct variable! Parentheses are mandatory: (*ptr).field, or simply use the cleaner arrow operator: ptr->field.

📝 Syntax

typedef struct {
    int x;
    int y;
} Point;

Point p = {10, 20};
Point *ptr = &p;

// Equivalent member access syntax forms:
int val1 = (*ptr).x; // Manual dereference with mandatory parentheses
int val2 = ptr->x;   // Arrow operator shorthand (Clean & Idiomatic!)

🔀 Dot (.) vs Arrow (->) Operator Matrix

Operator Operates On Example Syntax Meaning
Dot Operator (.) Struct Variable Instance student.gpa Access member gpa inside struct variable student.
Arrow Operator (->) Pointer to Struct ptr->gpa Dereference ptr and access member gpa ((*ptr).gpa).

🌱 Beginner Example: Dot vs Arrow Operator Comparison

#include <stdio.h>

typedef struct {
    int id;
    double balance;
} Account;

int main(void) {
    Account acc = {101, 1500.75};
    Account *ptr = &acc;

    // Dot Operator (Direct Variable)
    printf("Via Dot Operator   : ID = %d, Balance = $%.2lf\n", acc.id, acc.balance);

    // Arrow Operator (Pointer)
    printf("Via Arrow Operator : ID = %d, Balance = $%.2lf\n", ptr->id, ptr->balance);

    // Manual Dereference
    printf("Via Dereference    : ID = %d, Balance = $%.2lf\n", (*ptr).id, (*ptr).balance);

    return 0;
}

🌼 Intermediate Example: In-Place Mutation via Struct Pointer Function

#include <stdio.h>

typedef struct {
    char title[32];
    int quantity;
    double price;
} InventoryItem;

// Zero-Copy Function Parameter: In-Place Struct Mutation
void update_item_stock(InventoryItem *item, int added_qty, double new_price) {
    if (item == NULL) return;

    item->quantity += added_qty;
    item->price = new_price;
}

int main(void) {
    InventoryItem laptop = {"Gaming Laptop", 5, 1200.00};

    printf("Initial Stock: %d units @ $%.2lf\n", laptop.quantity, laptop.price);

    // Pass address of struct to update function
    update_item_stock(&laptop, 3, 1150.00);

    printf("Updated Stock: %d units @ $%.2lf (Mutated in-place!)\n",
           laptop.quantity, laptop.price);
    return 0;
}

🌲 Advanced Example: Self-Referential Structs (Linked List Node)

#include <stdio.h>
#include <stdlib.h>

typedef struct Node {
    int data;
    struct Node *next; // Self-referential pointer to next node in list
} Node;

int main(void) {
    // Manually link three nodes on the heap
    Node *head = (Node*)malloc(sizeof(Node));
    Node *second = (Node*)malloc(sizeof(Node));
    Node *third = (Node*)malloc(sizeof(Node));

    head->data = 10;   head->next = second;
    second->data = 20; second->next = third;
    third->data = 30;  third->next = NULL;

    // Traverse linked list using arrow operator
    printf("=== Traversing Arrow-Linked Nodes ===\n");
    Node *curr = head;
    while (curr != NULL) {
        printf("Node Data: %d\n", curr->data);
        curr = curr->next; // Advance to next node via arrow
    }

    free(head);
    free(second);
    free(third);
    return 0;
}

🔍 Line-by-Line Explanation

  • Account *ptr = &acc;: Stores the starting RAM memory address of the acc struct.
  • ptr->balance: Arrow operator dereferences ptr and reads the balance field offset in a single operation.
  • update_item_stock(&laptop, ...): Passes struct address so the function modifies the caller's laptop struct directly.
  • curr = curr->next;: Standard linked list traversal idiom following self-referential struct pointers.

💻 Expected Terminal Output

Via Dot Operator   : ID = 101, Balance = $1500.75
Via Arrow Operator : ID = 101, Balance = $1500.75
Via Dereference    : ID = 101, Balance = $1500.75
Initial Stock: 5 units @ $1200.00
Updated Stock: 8 units @ $1150.00 (Mutated in-place!)
=== Traversing Arrow-Linked Nodes ===
Node Data: 10
Node Data: 20
Node Data: 30

⚠️ Common Mistakes & Pitfalls

  • Forgetting Parentheses in Manual Dereference: Writing *ptr.field instead of (*ptr).field fails to compile due to dot operator precedence.
  • Using Dot Operator on Struct Pointer: Writing ptr.field when ptr is a pointer variable causes compilation errors. Use ptr->field.
  • Dereferencing NULL Struct Pointers: Calling ptr->field when ptr == NULL causes an instant Segmentation Fault crash.

📌 Important Rules & Limitations

  • Use dot (.) for struct variables; use arrow (->) for struct pointers.
  • Always verify if (ptr != NULL) before accessing struct fields via ptr->member.

🌐 Multilingual Explanation: English

The arrow operator (ptr->field) dereferences a struct pointer and accesses a member in one step. Passing struct pointers to functions avoids large stack copies and enables in-place mutation.

🌐 Multilingual Explanation: Hindi (Roman Script)

Arrow operator (ptr->field) struct pointer ke members ko access karne ke liye use hota hai. Large structs ko functions mein pointer dwara bhejne se memory aur CPU time bachta hai.

🌐 Multilingual Explanation: Marathi (Roman Script)

Struct pointer vaaparun members access karnyasathi arrow operator (ptr->field) vapartat. Function la struct pointer pass kelyas copy fast hote.

❓ Practice Questions

  1. Why is (*ptr).field equivalent to ptr->field?
  2. Why does *ptr.field fail to compile in C?
  3. Why is passing a struct pointer to a function faster than passing a struct by value?

🚀 Practical Coding Challenge

Write a C program named rectangle_pointer_calc.c that defines a Rectangle struct with length and width, and a function void scale_rectangle(Rectangle *r, double factor) that scales dimensions using the arrow operator.

🧭 Navigation & Breadcrumbs

← Previous: 01. Struct Declarations | Module 13 Guide | Next: 03. Arrays of Structs & Nested Structs →