Arrow operator -> in C/C++ with Examples
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);
}
|
Last Updated :
20 Mar, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...