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 geater 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:

  1. Arrow operator in structure:
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // C program to show Arrow operator
    // used in structure
      
    #include <stdio.h>
    #include <stdlib.h>
      
    // Creating the structure
    struct student {
        char name[80];
        int age;
        float percentage;
    };
      
    // Creating the structure object
    struct student* emp = NULL;
      
    // Driver code
    int main()
    {
        // Assigning memory to struct variable emp
        emp = (struct student*)
            malloc(sizeof(struct student));
      
        // Assigning value to age variable
        // of emp using arrow operator
        emp->age = 18;
      
        // Printing the assigned value to the variable
        printf("%d", emp->age);
      
        return 0;
    }

    chevron_right

    
    

    Output:

    18
    
  2. Arrow operator in unions:
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // C program to show Arrow operator
    // used in structure
      
    #include <stdio.h>
    #include <stdlib.h>
      
    // Creating the union
    union student {
        char name[80];
        int age;
        float percentage;
    };
      
    // Creating the union object
    union student* emp = NULL;
      
    // Driver code
    int main()
    {
        // Assigning memory to struct variable emp
        emp = (union student*)
            malloc(sizeof(union student));
      
        // Assigning value to age variable
        // of emp using arrow operator
        emp->age = 18;
      
        // DIsplaying the assigned value to the variable
        printf("%d", emp->age);
    }

    chevron_right

    
    

    Output:

    18
    


My Personal Notes arrow_drop_up

Intern at GeeksforGeeks

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.