Accessing structure members through a pointer in C: which operator should be used to reach a field of a struct via a pointer variable?

Difficulty: Easy

Correct Answer: ->

Explanation:


Introduction / Context:
C offers two syntaxes for accessing structure members: the dot operator for a direct struct object and the arrow operator for a pointer to a struct. Choosing the correct operator improves clarity and avoids common compiler errors.



Given Data / Assumptions:

  • We have a pointer variable p of type struct S that points to a valid struct S object.
  • We want to access one of its members, say field.


Concept / Approach:
When working with a pointer to a struct, the expression p->field is syntactic sugar for (*p).field. The arrow operator both dereferences the pointer and selects the member in one step. By contrast, the dot operator expects an actual struct object (not a pointer). The unary * operator alone yields the struct object from the pointer but still requires . to access a specific member.



Step-by-Step Solution:
Given struct S s; struct S *p = &s; to access s.field through p, write p->field.Equivalent but longer form: (*p).field.Using p.field is a type error because p is not a struct object.



Verification / Alternative check:
Compile a snippet using both p->field and (p).field to see they produce the same code in practice.



Why Other Options Are Wrong:

  • . applies to non-pointer struct objects.
  • & is the address-of operator, unrelated to member access.
  • alone dereferences but does not select a member.


Common Pitfalls:
Forgetting parentheses in (*p).field; without them, *p.field binds incorrectly due to precedence.



Final Answer:
->.

More Questions from Pointers

Discussion & Comments

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