In this post, we focus on the arrow operator in C. The C programming language offers a variety of operators to work with and manipulate data sets. One of these operators is the arrow operator.

Let’s dive right in!

How Does the Arrow Operator Work in C?

In C, the arrow operator allows access to the data of a structure or union. This operator (->) is made up of a minus sign (-) and a greater-than sign (>). It enables referencing the elements of a structure or union pointed to by a pointer variable.

Let’s take a closer look at the syntax of this operator.

Syntax of the Arrow Operator (->)

Here’s the general syntax:

(pointer_variable)->(variable) = value;

The arrow operator is used with a pointer variable. This means the operator accesses the address (variable) pointed to by the pointer and stores a value there.

Let’s look at some practical examples.

Examples of the Arrow Operator (->)

In the following example, we’ve created a structure called Movie_info. We assign a pointer to this structure and dynamically allocate memory using the C function malloc().

Arrow Operator for Data Access in a C Structure:

#include <stdio.h>
#include <stdlib.h>

struct Movie_info
{ 
    char *name; 
    char *ACC; 
};
 
int main()
{
     struct Movie_info* M;
     M = (struct Movie_info*) 
        malloc(sizeof(struct Movie_info)); 
     
     M->name = "C with JournalDev";
     M->ACC = "A";
 
     printf("Movie Information:");
     printf("\nName: %s", M->name);
     printf("\nACC: %s", M->ACC);
     return 0;
}

In this example, we access the values of the data members using the arrow operator (->).

Output:

Movie Information:
Name: C with JournalDev
ACC: A

Now, let’s see how to access the data members of a union using the arrow operator.

Arrow Operator for Accessing Data Members of a Union in C:

#include <stdio.h>
#include <stdlib.h>

union Movie_info
{ 
    int id;
    float net_val;
};
 
int main()
{
     union Movie_info* M;
     M = (union Movie_info*) 
        malloc(sizeof(union Movie_info)); 
     printf("Movie Information:\n");
     M->id = 01;
     printf("\n ID: %d", M->id);
     M->net_val = 125.45;
     printf("\n NET VALUE: %.1f", M->net_val);
     return 0;
}

Similar to the structure, we created a union Movie_info and accessed its values using the arrow operator.

Output:

Movie Information:
ID: 1
NET VALUE: 125.4

Conclusion

We’ve now reached the end of this topic. The arrow operator in C is a powerful tool for accessing the data of structures and unions referenced by pointers. If you have any questions, feel free to leave a comment!

Create a Free Account

Register now and get access to our Cloud Services.

Posts you might be interested in: