In C, does the . operator access members from a structure variable (as opposed to a pointer)?

Difficulty: Easy

Correct Answer: Correct — use . with a structure (or union) variable, not a pointer

Explanation:


Introduction / Context:
Member access syntax is fundamental in C. The . operator and the -> operator apply to different operand types.


Given Data / Assumptions:

  • A structure (or union) value.
  • A pointer to such a value may also exist.


Concept / Approach:
Use . when you have an actual object; use -> when you have a pointer. This rule is identical for structs and unions.


Step-by-Step Solution:
1) Let s be a struct value: access as s.member.2) Let ps be a pointer: access as ps->member (i.e., (*ps).member).3) Therefore . is correct for variables, while -> is for pointers.


Verification / Alternative check:
Compilers enforce this; using . on a pointer produces an error unless you dereference first.


Why Other Options Are Wrong:
Option B: Reverses the rule.
Option C: C has no public/private for structs.
Option D: Nesting does not change the operator rule.
Option E: . and -> are not interchangeable.


Common Pitfalls:
Forgetting to dereference pointers or assuming both operators behave the same leads to confusing errors.


Final Answer:
Correct — use . with a structure (or union) variable, not a pointer.

Discussion & Comments

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