c语言结构体定义的函数的返回值
时间: 2024-06-13 18:10:02 浏览: 23
C语言结构体定义的函数的返回值可以是结构体类型本身,也可以是结构体类型的指针。下面是两个例子:
1. 返回结构体类型本身
```c
struct student {
char name[20];
int age;
};
struct student getInfo() {
struct student s;
printf("请输入姓名:");
scanf("%s", s.name);
printf("请输入年龄:");
scanf("%d", &s.age);
return s;
}
int main() {
struct student s = getInfo();
printf("姓名:%s,年龄:%d\n", s.name, s.age);
return 0;
}
```
2. 返回结构体类型的指针
```c
struct student {
char name[20];
int age;
};
struct student *getInfo() {
struct student *s = (struct student *)malloc(sizeof(struct student));
printf("请输入姓名:");
scanf("%s", s->name);
printf("请输入年龄:");
scanf("%d", &s->age);
return s;
}
int main() {
struct student *s = getInfo();
printf("姓名:%s,年龄:%d\n", s->name, s->age);
free(s);
return 0;
}
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![application/msword](https://img-home.csdnimg.cn/images/20210720083327.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)
![](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)