亿迅智能制造网
工业4.0先进制造技术信息网站!
首页 | 制造技术 | 制造设备 | 工业物联网 | 工业材料 | 设备保养维修 | 工业编程 |
home  MfgRobots >> 亿迅智能制造网 >  >> Industrial programming >> C语言

C语言结构体进阶:传递、返回与引用处理

C语言结构体进阶:传递、返回与引用处理

C语言中结构体允许将相关数据组织为单一实体。本指南讲解结构体的三项核心操作:传递给函数、从函数返回、按引用操作。每节含简明解释和可运行示例。


向函数传递结构体

像内置类型一样,结构体变量可直接传递给函数。建议先复习 C结构体、C函数 和 用户定义函数。

下例演示将 struct student 传递给打印其内容的函数。

#include <stdio.h>
struct student {
    char name[50];
    int age;
};
// 函数原型
void display(struct student s);
int main() {
    struct student s1;
    printf("输入姓名: ");
    scanf("%[^ ]%%*c", s1.name); // 读至换行
    printf("输入年龄: ");
    scanf("%d", &s1.age);
    display(s1); // 传递结构体
    return 0;
}
void display(struct student s) {
    printf("\n显示信息\n");
    printf("Name: %s", s.name);
    printf("\nAge: %d", s.age);
}

输出

输入姓名: Bond
输入年龄: 13
显示信息
Name: Bond
Age: 13

从函数返回结构体

函数可返回整个结构体,实现数据收集与处理的清晰分离。下例在函数内收集学生信息并返回 main。

#include <stdio.h>
struct student {
    char name[50];
    int age;
};
// 函数原型
struct student getInformation();
int main() {
    struct student s;
    s = getInformation();
    printf("\n显示信息\n");
    printf("Name: %s", s.name);
    printf("\nAge: %d", s.age);
    return 0;
}
struct student getInformation() {
    struct student s1;
    printf("输入姓名: ");
    scanf("%[^ ]%%*c", s1.name);
    printf("输入年龄: ");
    scanf("%d", &s1.age);
    return s1;
}

函数返回类型与返回的结构体匹配,保证类型安全和清晰度。


按引用传递结构体

需函数修改结构体时,传递其地址(即指针)。这类似于按引用传递内置类型。下例将两个复数相加并通过指针存储结果。

#include <stdio.h>
typedef struct Complex {
    float real;
    float imag;
} complex;
void addNumbers(complex c1, complex c2, complex *result);
int main() {
    complex c1, c2, result;
    printf("第一个数:\n");
    printf("实部: ");
    scanf("%f", &c1.real);
    printf("虚部: ");
    scanf("%f", &c1.imag);
    printf("第二个数:\n");
    printf("实部: ");
    scanf("%f", &c2.real);
    printf("虚部: ");
    scanf("%f", &c2.imag);
    addNumbers(c1, c2, &result);
    printf("\nresult.real = %.1f\n", result.real);
    printf("result.imag = %.1f", result.imag);
    return 0;
}
void addNumbers(complex c1, complex c2, complex *result) {
    result->real = c1.real + c2.real;
    result->imag = c1.imag + c2.imag;
}

输出

第一个数,
实部: 1.1
虚部: -2.4
第二个数,
实部: 3.4
虚部: -3.2
result.real = 4.5
result.imag = -5.6

因 result 按引用传递,addNumbers 内的修改立即影响 main 中的变量。


掌握这些技术,你能编写更模块化、可读、高效的C代码,充分发挥结构体威力。

C语言

  1. 电力变压器全解析:原理、结构、工业应用与运维要点
  2. 车床的 15 个关键部件及其功能详解
  3. 深入理解 C# 结构体:定义、用法与与类的核心差异
  4. C++ 友元函数与友元类:突破访问控制的利器
  5. 精通C语言结构体:定义、变量、访问与进阶示例
  6. 精通C语言结构体与指针:实战指南
  7. C++ Struct 与 Class 核心差异、语法及最佳实践
  8. C 程序结构详解:Hello World 实例与编译运行全流程
  9. C 语言数据类型完全指南:整型、浮点型、void 与派生类型
  10. C 语言常量与字面量完全指南:类型、用法与最佳实践
  11. C 语言函数详解:定义、声明、调用与参数传递
  12. C++重载机制深度解析:函数重载与运算符重载全攻略