C语言-结构体笔记2
与内置类型的变量类似,您也可以将结构变量传递给函数。
将结构传递给函数的方法:
#include <stdio.h>
struct student {
char name[50];
int age;
};
// function prototype
void display(struct student s);
int main() {
struct student s1;
printf("Enter name: ");
// read string input from the user until \n is entered
// \n is discarded
scanf("%[^\n]%*c", s1.name);
printf("Enter age: ");
scanf("%d", &s1.age);
display(s1); // passing struct as an argument
return 0;
}
void display(struct student s) {
printf("\nDisplaying information\n");
printf("Name: %s", s.name);
printf("\nAge: %d", s.age);
}
输出:
Enter name: Bond
Enter age: 13
Displaying information
Name: Bond
Age: 13
这里创建了struct student类型的struct变量s1,使用display(s1)将变量传递给display()函数
从函数返回结构
从函数返回结构的方法:
#include <stdio.h>
struct student
{