• 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 会发生报错。

  • 相关阅读:
    GPS坐标转化距离(短距离模型公式)
    jquery ajax 同步异步的执行
    视频播放的基本原理
    [css或js控制图片自适应]
    asp.net中js和jquery调用ashx的不同方法分享,需要的朋友可以参考一下
    [转载]在网页中插入media,RealPlayer等控件
    数组的几种排序算法的实现(3)
    -- HTML标记大全参考手册[推荐]
    数组的几种排序算法的实现(2)
    数组的几种排序算法的实现(1)
  • 原文地址:https://www.cnblogs.com/liujiaxin2018/p/14852075.html
Copyright © 2020-2023  润新知