In C, when should you use the -> operator to access members, and what kinds of types does it work with?

Difficulty: Easy

Correct Answer: When you have a pointer to a struct or a pointer to a union

Explanation:


Introduction / Context:
This tests knowledge of C member-access operators: the dot (.) and arrow (->). Understanding when each applies prevents common pointer and syntax errors.


Given Data / Assumptions:

  • We are writing standard C.
  • We have both structure and union types available.
  • We may have variables and pointers to these aggregate types.


Concept / Approach:
Use . with an actual object (non-pointer). Use -> with a pointer to an object. The rule applies identically to structs and unions: . for objects, -> for pointers.


Step-by-Step Solution:
1) If s is a struct value, s.member uses .2) If ps is a pointer to struct, ps->member is shorthand for (*ps).member.3) The same rule holds for unions and pointers to unions.4) Therefore, -> is correct when you have a pointer to a struct or union.


Verification / Alternative check:
Compile small examples: accessing via ps->x compiles if ps is a pointer; using ps.x will fail. Similarly for unions.


Why Other Options Are Wrong:
Option B: . is required for non-pointer objects, not ->.
Option C: Arrays do not use -> for element or member access.
Option D: . and -> are not interchangeable.
Option E: -> also works with pointers to unions, not only structures.


Common Pitfalls:
Forgetting to dereference pointers before using . leads to errors; -> already performs that dereference syntactically.


Final Answer:
Use -> when you have a pointer to a struct or a pointer to a union.

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion