C语言将结构体传入函数怎么写
时间: 2024-05-06 08:22:12 浏览: 8
在C语言中,可以通过以下两种方式将结构体传入函数:
1. 传递结构体变量的地址
函数定义时,参数类型应该是结构体指针类型,然后在函数调用时,将结构体变量的地址作为实参传递给函数。
示例代码:
```
#include <stdio.h>
struct Student {
char name[20];
int age;
float score;
};
void printStudent(struct Student *s) {
printf("Name: %s\n", s->name);
printf("Age: %d\n", s->age);
printf("Score: %.2f\n", s->score);
}
int main() {
struct Student s = {"Tom", 18, 89.5};
printStudent(&s); // 传递结构体变量的地址
return 0;
}
```
2. 传递结构体变量本身
函数定义时,参数类型应该是结构体类型,然后在函数调用时,将结构体变量本身作为实参传递给函数。
示例代码:
```
#include <stdio.h>
struct Student {
char name[20];
int age;
float score;
};
void printStudent(struct Student s) {
printf("Name: %s\n", s.name);
printf("Age: %d\n", s.age);
printf("Score: %.2f\n", s.score);
}
int main() {
struct Student s = {"Tom", 18, 89.5};
printStudent(s); // 传递结构体变量本身
return 0;
}
```