zoukankan      html  css  js  c++  java
  • c语言中将结构体对象指针作为函数的参数实现对结构体成员的修改

    c语言中将结构体对象指针作为函数的参数实现对结构体成员的修改。

    1、

    #include <stdio.h>
    
    #define NAME_LEN 64
    
    struct student{
        char name[NAME_LEN];
        int height;
        float weight;
        long schols;
    };
    
    void hiroko(struct student *x)  // 将struct student类型的结构体对象的指针作为函数的形参 
    {
        if((*x).height < 180)  // x为结构体对象的指针,使用指针运算符*,可以访问结构体对象实体,结合.句点运算符,可以访问结构体成员,从而对结构体成员进行修改。 
            (*x).height = 180;
        if((*x).weight > 80)
            (*x).weight = 80; //因为传入的是结构体对象的指针,因此可以实现对传入的结构体对象的成员进行修改 
    }
    
    int main(void)
    {
        struct student sanaka = {"Sanaka", 173, 87.3, 80000};
        
        hiroko(&sanaka);  //函数的实参需要是指针,使用取址运算符&获取对象sanaka的地址 
        
        printf("sanaka.name:  %s
    ", sanaka.name);
        printf("sanaka.height:  %d
    ", sanaka.height);
        printf("sanaka.weight:  %.2f
    ", sanaka.weight);
        printf("sanaka.schols: %ld
    ", sanaka.schols);
        
        return 0;
    }

    等价于以下程序(使用箭头运算符 ->)

    #include <stdio.h>
    
    #define NAME_LEN 64
    
    struct student{
        char name[NAME_LEN];
        int height;
        float weight;
        long schols;
    };
    
    void fun(struct student *x) // 函数的形参为指向struct student型的对象的指针 
    {
        if(x -> height < 180)  // 指针 + ->(箭头运算符)+ 结构体成员名称 可以访问结构体成员,从而实现结构体成员值的修改 
            x -> height = 180;
        if(x -> weight > 80)   // 箭头运算符 -> 应用于结构体对象指针,访问结构体对象的结构体成员 
            x -> weight = 80;
    }
    
    int main(void)
    {
        struct student sanaka = {"Sanaka", 173, 87.3, 80000};
        
        fun(&sanaka);  // 函数的形参为struct student型的结构体对象指针, 因此使用取址运算符&传入结构体对象sanaka的地址(指针), 
        
        printf("sanaka.name:  %s
    ", sanaka.name);
        printf("sanaka.height:  %d
    ", sanaka.height);
        printf("sanaka.weight:  %.2f
    ", sanaka.weight);
        printf("sanaka.schols:  %ld
    ", sanaka.schols);
        
        return 0;
    }

     箭头运算符 只能应用于结构体对象的指针,访问结构体对象的成员, 不能应用于一般的结构体对象。比如 sanaka -> height 会发生报错。

  • 相关阅读:
    程序员,如何从平庸走向理想?
    【Hadoop】HA 场景下访问 HDFS JAVA API Client
    hive 和Hbase的pom文件
    wxpython多线程通信的应用-实现边录音边绘制音谱图
    wxpython多线程间通信
    LeetCode 92. ReverseLinkedII
    pip换源安装
    wxpython绘制音频
    python读取wav文件并播放[pyaudio/wave]
    Python绘制wav文件音频图(静态)[matplotlib/wave]
  • 原文地址:https://www.cnblogs.com/liujiaxin2018/p/14852075.html
Copyright © 2011-2022 走看看