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

 

posted @   小鲨鱼2018  阅读(1828)  评论(0编辑  收藏  举报
编辑推荐:
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
点击右上角即可分享
微信分享提示