c语言结构题作为函数的形式参数
时间: 2023-07-09 19:43:07 浏览: 46
当我们将结构作为函数的形参时,可以使用以下两种方式:
1. 传递结构体变量的地址作为函数的参数:
```c
struct student {
char name[20];
int age;
float marks;
};
void display(struct student *s) {
printf("Name: %s\n", s->name);
printf("Age: %d\n", s->age);
printf("Marks: %.2f\n", s->marks);
}
int main() {
struct student s = {"John", 18, 85.5};
display(&s);
return 0;
}
```
2. 将结构体变量作为函数的参数:
```c
struct student {
char name[20];
int age;
float marks;
};
void display(struct student s) {
printf("Name: %s\n", s.name);
printf("Age: %d\n", s.age);
printf("Marks: %.2f\n", s.marks);
}
int main() {
struct student s = {"John", 18, 85.5};
display(s);
return 0;
}
```
在第一个例子中,我们将结构体变量`s`的地址作为参数传递给`display`函数,函数内部使用指针访问结构体成员。
在第二个例子中,我们将结构体变量`s`本身作为参数传递给`display`函数。这种方式会导致结构体的拷贝,因此可能会增加内存使用和执行时间。