Difference Between Dot and Arrow Operators in C

For Complete YouTube Video: Click Here

We will try to understand the Difference Between Dot and Arrow Operators in C in this class.

We have already covered the concepts of using the dot operator to access the elements of structures in detail.

In C Programming, we have the arrow operator to access the structure elements.

In this class, we will understand the use of the arrow operator compared to the dot operator.

Difference Between Dot and Arrow Operators in C

Example

To understand the difference, consider the programming example as shown below.

Difference Between Dot and Arrow Operators in C
Difference Between Dot and Arrow Operators in C

In the below example, we have a structure student with member stuno of integer type.

The structure variable is stu1.

In the program, we have a pointer to the student structure by name pstu.

Now consider the two print statements in the program as shown in the image below.

Difference Between Dot and Arrow Operators in C 1
Difference Between Dot and Arrow Operators in C 1

The first print statement uses a dot operator to access the structure member.

In the second print statement, we use the pointer variable to access the structure members.

The declaration *pstu.stu1 uses the dot operator.

The above declaration produces an error.

The error generates because the dot operator has the highest precedence than the star operator.

The C compiler will consider the statement as *(pstu.stu1).

This declaration will produce an error.

The correct way to declare to access the members of the structures using pointers is *(pstu).stu1.

As paratheses are cumbersome all the time, C is providing the arrow operator to access the elements using pointers.

The declaration *(pstu).stu1 can also be done by using pstu->stu1.

Instead of the parentheses and star operator, we can use the arrow operator.