122k views
4 votes
When should you access structure members using the dot operator(.) versus the arrow operator(->)?

User Patonz
by
9.1k points

1 Answer

5 votes

Final answer:

When working with structures, you use the dot operator to access members when the variable is not a pointer, and the arrow operator when the variable is a pointer.

Step-by-step explanation:

When working with structures in programming, you access structure members using the dot operator (.) when the variable you are accessing is of structure type and the variable itself is not a pointer. For example:

struct Student {
int id;
char name[20];
};

struct Student s;
s.id = 12345;
s.name = "John Doe";

On the other hand, you access structure members using the arrow operator (->) when the variable you are accessing is a pointer to a structure. For example:

struct Student {
int id;
char name[20];
};

struct Student* p = &s;
p->id = 12345;
p->name = "John Doe";

By using the arrow operator, you are dereferencing the pointer to access the structure members.

User Ndeye
by
8.2k points