大话C语言:第41篇 结构体与函数的关系

1 结构体作为函数的参数

结构体作为函数的参数,存在两种传递方式:

  • 值传递:将结构体的值拷贝一份传递给函数,函数内部对该结构体的修改不会影响到原来的结构体变量。

代码示例:

#include <stdio.h>
#include <string.h>

// 结构体类型的定义
struct Student 
{  
    char name[20];  
    int age;  
    float score;  
};  

// 函数定义
void ShowStudent(struct Student stu) 
{
    strcpy(stu.name, "jack");
    stu.age = 22;
    stu.score = 98.5f;
    printf("ShowStudent函数里,该学生:%s, %d, %.1f\n", stu.name, stu.age, stu.score);
}

int main() 
{
    // 定义结构体变量
    struct Student stu = {"peter", 20, 90.5f};
    
    // 调用函数,值传递
    ShowStudent(stu);
    
    // 打印成员变量
    printf("main函数里,该学生:%s, %d, %.1f\n", stu.name, stu.age, stu.score);

    return 0;
}
  • 地址传递:将结构体的地址传递给函数,函数内部可以通过该地址来访问原变量,并对其进行修改。

代码示例:

#include <stdio.h>
#include <string.h>

// 结构体类型的定义
struct Student 
{  
    char name[20];  
    int age;  
    float score;  
};  

// 函数定义
void ShowStudent(struct Student *stu) 
{
    strcpy(stu->name, "jack");
    stu->age = 22;
    stu->score = 98.5f;
    printf("ShowStudent函数里,该学生:%s, %d, %.1f\n", stu->name, stu->age, stu->score);
}

int main() 
{
    // 定义结构体变量
    struct Student stu = {"peter", 20, 90.5f};
    // 打印成员变量
    printf("main函数里,ShowStudent函数调用前,该学生:%s, %d, %.1f\n", stu.name, stu.age, stu.score);
    
    // 调用函数,值传递
    ShowStudent(&stu);
    
    // 打印成员变量
    printf("main函数里,ShowStudent函数调用后,该学生:%s, %d, %.1f\n", stu.name, stu.age, stu.score);

    return 0;
}

2 结构体作为函数的返回值

结构体作为函数的返回值,存在两种返回方式:

  • 直接返回结构体:如果结构体较小,内容简单,可以直接将其作为函数的返回值。这种方式简单直观,不需要额外的内存管理操作。

代码示例:

#include <stdio.h>

// 结构体类型的定义
struct Student 
{  
    char name[20];  
    int age;  
    float score;  
};

// 直接返回结构体
struct Student GenerateStudent()
{
    struct Student stu = {"peter", 20, 90.5f};
    
    return stu;
}


int main()
{
    struct Student stu = GenerateStudent();
    
    printf("该学生:%s, %d, %.1f\n", stu.name, stu.age, stu.score);
    
    return 0;
}

注意,当结构体较大时,直接返回可能会导致性能问题,因为函数返回时会复制整个结构体。

  • 返回结构体指针:当结构体较大或者需要在函数外部修改结构体内容时,通常使用返回结构体指针的方式。这样可以避免大量数据的复制,提高性能。

代码示例:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

// 结构体类型的定义
struct Student 
{  
    char name[20];  
    int age;  
    float score;  
}; 
  
struct Student* GenerateStudent() 
{  
    struct Student *stu = (struct Student*)malloc(sizeof(struct Student));  
    if (stu != NULL) {  
        strcpy(stu->name, "jack");
        stu->age = 22;
        stu->score = 98.5f;
    }
    
    return stu; // 返回结构体指针  
}  
  
int main()
{  
    struct Student *stu = GenerateStudent();  
    
    if (stu != NULL) 
    {  
        printf("该学生:%s, %d, %.1f\n", stu->name, stu->age, stu->score);
        
        // 使用完毕后释放内存   
        free(stu); 
        stu = NULL;
    }  
    
    return 0;  
}

注意,使用结构体指针需要谨慎处理内存管理问题,避免内存泄漏或野指针等问题。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值