如何在无参函数中使用外界结构体
时间: 2023-10-30 21:04:49 浏览: 36
要在无参函数中使用外界结构体,可以通过以下两种方式之一实现:
1.将结构体作为全局变量,在函数中直接使用它:
```
#include <stdio.h>
struct student {
char name[20];
int age;
};
struct student stu = {"Tom", 18};
void print_student() {
printf("Name: %s\n", stu.name);
printf("Age: %d\n", stu.age);
}
int main() {
print_student();
return 0;
}
```
2.将结构体指针作为函数参数,在函数中使用它:
```
#include <stdio.h>
struct student {
char name[20];
int age;
};
void print_student(struct student *stu) {
printf("Name: %s\n", stu->name);
printf("Age: %d\n", stu->age);
}
int main() {
struct student stu = {"Tom", 18};
print_student(&stu);
return 0;
}
```
在这两种方法中,我们都可以在函数中使用外部结构体。第一种方法将结构体作为全局变量,所以我们可以在任何函数中使用它。第二种方法将结构体指针作为函数参数,所以我们需要将结构体的地址传递给函数。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pptx](https://img-home.csdnimg.cn/images/20210720083543.png)