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:
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