An Arrow operator in C/C++ allows to access elements in Structures and Unions. It is used with a pointer variable pointing to a structure or union. The arrow operator is formed by using a minus sign, followed by the greater than symbol as shown below.
Syntax:
(pointer_name)->(variable_name)
Operation: The -> operator in C or C++ gives the value held by variable_name to structure or union variable pointer_name.
Difference between Dot(.) and Arrow(->) operator:
- The Dot(.) operator is used to normally access members of a structure or union.
- The Arrow(->) operator exists to access the members of the structure or the unions using pointers.
Examples:
- Arrow operator in structure:
C
#include <stdio.h>
#include <stdlib.h>
struct student {
char name[80];
int age;
float percentage;
};
struct student* emp = NULL;
int main()
{
emp = ( struct student*)
malloc ( sizeof ( struct student));
emp->age = 18;
printf ( "%d" , emp->age);
return 0;
}
|
C++
#include <iostream>
using namespace std;
struct student {
char name[80];
int age;
float percentage;
};
struct student* emp = NULL;
int main()
{
emp = ( struct student*)
malloc ( sizeof ( struct student));
emp->age = 18;
cout << " " << emp->age;
return 0;
}
|
Javascript
let emp = null ;
class Student {
constructor(name, age, percentage) {
this .name = name;
this .age = age;
this .percentage = percentage;
}
}
emp = new Student( '' , 0, 0);
emp.age = 18;
console.log( ' ' + emp.age);
|
Time complexity: O(1).
Auxiliary space: O(n). // n is the size of memory that is being dynamically allocated using the malloc function to store the structure student. The amount of memory used is proportional to the size of the structure and the number
- Arrow operator in unions:
C++
#include <iostream>
using namespace std;
union student {
char name[80];
int age;
float percentage;
};
union student* emp = NULL;
int main()
{
emp = ( union student*)
malloc ( sizeof ( union student));
emp->age = 18;
cout << "" << emp->age;
}
|
C
#include <stdio.h>
#include <stdlib.h>
union student {
char name[80];
int age;
float percentage;
};
union student* emp = NULL;
int main()
{
emp = ( union student*)
malloc ( sizeof ( union student));
emp->age = 18;
printf ( "%d" , emp->age);
}
|
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!
Last Updated :
20 Mar, 2023
Like Article
Save Article