Array operators are used extensively in most large programs. But why is this arrow used? Or what is the reason for using it?

It is basically an access operator. Variables can be declared both at compile time and at run time in C/C++. The way we usually declare variables is to allocate memory at compile time. And pointers are used to dynamically allocate memory at run time. The arrow operator (“->”) is used to access any member of a Struct, Union or Class of this pointer type. In general, members are accessed using the dot (.) operator. Now we see two examples, one with pointers and one without pointers –

#include iostream
using namespace std;

struct student{
    int roll;
    char *name;
};

int main()
{
    student std;
    std.roll=100120;
    std.name="Shahinur";
    
    cout<<std.roll<<endl<<std.name;

    return 0;
}

The code used above uses the dot operator. Let’s look at the following program using pointers in exactly the same way –

#include iostream 
using namespace std;

struct student{
    int roll;
    char *name;
};

int main()
{
    student std, *stdptr;
    stdptr=&std; // Assigning an address to the pointer
    std.roll=100120;
    std.name="Shahinur";
    
    cout<<std.roll<<endl<<std.name<<endl; // Using . operator
    cout<<stdptr->roll<<endl<stdptr->name; // Using arrow operator

    return 0;
}

The above code uses the arrow operator to show how it can work with pointers as references.

0 0 votes
Article Rating
0
Would love your thoughts, please comment.x
()
x