📜  箭头运算符->在C / C++中带有示例

📅  最后修改于: 2021-05-28 05:33:14             🧑  作者: Mango

C / C++中Arrow运算符允许访问结构和联合中的元素。它与指向结构或联合的指针变量一起使用。箭头运算符由减号组成,后跟加特号而不是符号,如下所示。

句法:

(pointer_name)->(variable_name)

操作:用C或C++的->运算符将variable_name持有的值赋予结构或并集变量pointer_name。

Dot(。)和Arrow(->)运算符之间的区别:

  • Dot(。)运算符通常用于访问结构或联合的成员。
  • 存在Arrow(->)运算符以使用指针访问结构的成员或联合。

例子:

  1. 箭头运算符的结构:
    // C program to show Arrow operator
    // used in structure
      
    #include 
    #include 
      
    // 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;
    }
    
    输出:
    18
    
  2. 联合中的箭头运算符:
    // C program to show Arrow operator
    // used in structure
      
    #include 
    #include 
      
    // 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);
    }
    
    输出:
    18
    

如果您希望与行业专家一起参加现场课程,请参阅《 Geeks现场课程》和《 Geeks现场课程美国》。