微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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\n", sanaka.name);
    printf("sanaka.height:  %d\n", sanaka.height);
    printf("sanaka.weight:  %.2f\n", sanaka.weight);
    printf("sanaka.schols: %ld\n", 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\n", sanaka.name);
    printf("sanaka.height:  %d\n", sanaka.height);
    printf("sanaka.weight:  %.2f\n", sanaka.weight);
    printf("sanaka.schols:  %ld\n", sanaka.schols);
    
    return 0;
}

 

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

 

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐