函数与结构体
函数把代码组织成可复用的模块;结构体(struct)把不同类型的数据打包成一个整体,是 C 里"面向对象"的雏形。
函数
返回类型 函数名(参数列表) { 函数体 }。函数要先声明(原型)再调用。传值传参拷贝一份,传指针可以修改原值。
结构体
struct 定义字段集合;typedef 给类型起别名(typedef struct { ... } Student; 之后直接用 Student)。
结构体与指针
结构体指针用 -> 访问成员(p->name),普通变量用 . 访问(s.name)。
代码示例
#include <stdio.h>
#include <string.h>
// 结构体 + typedef
typedef struct {
char name[20];
int age;
double score;
} Student;
// 函数:传值
int add(int a, int b) {
return a + b;
}
// 函数:传指针(修改原值)
void celebrate(Student *s) {
s->score += 5;
}
int main() {
Student s;
strcpy(s.name, "张三");
s.age = 20;
s.score = 85.5;
printf("姓名: %s, 年龄: %d, 分数: %.1f\n",
s.name, s.age, s.score);
celebrate(&s); // 传地址
printf("加分后: %.1f\n", s.score);
printf("3 + 4 = %d\n", add(3, 4));
return 0;
}