结构体作函数参数
#include <stdio.h> struct Student { int num; char name[20]; char sex; int age; double score; char addr[30]; }; void print(struct Student s) { printf("%d %s %c\n", s.num, s.name, s.sex); //可再加…… return; } int main() { struct Student student1,student2; struct Student *p_stu; student1.num=10001; student2.age=120; p_stu=&student2; print(student1); print(*p_stu); return 0; }
当结构体成员又是结构体……
#include <stdio.h> struct Date { int month; int day; int year; }; struct Student { int num; char name[20]; char sex; struct Date birthday; float score; } student1,student2= {10002,"Wang Li",'f',5,23,1982,89.5}; int main( ) { student1=student2; printf("%d\n", student1.num); printf("%s\n", student1.name); printf("%c\n", student1.sex); printf("%d/%d/%d\n", student1.birthday.month, student1.birthday.day, student1.birthday.year); printf("%.1f\n", student1.score); return 0; }
结构体的成员是数组
#include <stdio.h> #include <string.h> struct Student { int num; char name[10]; double score[3]; }; void print(struct Student); int main( ) { struct Student stu; stu.num=12345; strcpy(stu.name, "Li Fung"); stu.score[0]=67.5; stu.score[1]=89; stu.score[2]=78.5; print(stu); printf("%d %s ", stu.num, stu.name); printf("%.1f %.1f %.1f\n", stu.score[0], stu.score[1], stu.score[2]); return 0; }
void print(struct Student s)
{
printf("%d %s ", s.num, s.name);
printf("%.1f %.1f %.1f\n", s.score[0], s.score[1], s.score[2]);
}