>结构体的成员变量可以是另一个结构体类型的变量struct Student {struct Dateint num;char name[20] :int year;char sex;int month;int age;int day;struct Date birthday;7:char addr[30];版权所有@陈哲birthday5addrnumnamesexagedaymonthyear6
版 权 所 有 © 陈 哲 保 留 所 有 权 利 ➢结构体的成员变量可以是另一个结构体 类型的变量。 struct Date { int year; int month; int day; }; 6 num name sex age birthday addr year month day struct Student { int num; char name[20]; char sex; int age; struct Date birthday; char addr[30]; };
>可以在声明结构体类型的同时定义变量语法:struct「结构体名]【成员表列7变量名表列;>例如:struct Student {int num;可以省略char name[20l;char sex;版权所有@陈哲保留所有权利int age;float score;char addr[30l; studentl, student2;
版 权 所 有 © 陈 哲 保 留 所 有 权 利 ➢可以在声明结构体类型的同时定义变量。 语法: struct [结构体名] { 成员表列 } 变量名表列; ➢例如: struct Student { int num; char name[20]; char sex; int age; float score; char addr[30]; } student1, student2; 7 可以省略
>结构体变量的初始化struct Student1long int num;char nam[20] ;char sexchar addr[20:10101,"Li Si"l'M',"1 Nanjing Road"l :a版权所有陈暂保留所有权利8
版 权 所 有 © 陈 哲 保 留 所 有 权 利 ➢结构体变量的初始化。 struct Student { long int num; char name[20]; char sex; char addr[20]; } a = { 10101,"Li Si",'M',"1 Nanjing Road"}; 8
>结构体变量的访问:访问成员变量的语法:结构体变量名.成员变量名。struct Student a, b;//错!不能整体输入结构体变量的成员变量的值scanf("%ld,%s,%c,%s|n",&a) ;scanf("%ld",&a.num);/通过成员变量的地址输入scanf("%s".&a.name);//通过成员变量的地址输入a.num=10010;//成员变量相当于普通变量b.num = a.num + 1;b=a://同类型的结构体变量可互相赋值版权所有@陈暂保留所有权利printf("%p",&a)://输出结构体变量的地址//错!不能整体输出结构体变量的所有成员printf("%ld, %s.s,%c,%sln".printf("num:%ld/nname:%s/nsex:%c|naddress:%s)n"a.num, a.name, a. sex, a.addr):9
版 权 所 有 © 陈 哲 保 留 所 有 权 利 ➢结构体变量的访问:访问成员变量的语 法:结构体变量名.成员变量名。 struct Student a, b; //错!不能整体输入结构体变量的成员变量的值 scanf("%ld,%s,%c,%s\n", &a); scanf("%ld", &a.num); // 通过成员变量的地址输入 scanf("%s", &a.name); // 通过成员变量的地址输入 a.num = 10010; // 成员变量相当于普通变量 b.num = a.num + 1; b = a; // 同类型的结构体变量可互相赋值 printf("%p", &a); // 输出结构体变量的地址 // 错!不能整体输出结构体变量的所有成员 printf("%ld, %s, %c, %s\n", a); printf("num:%ld\nname:%s\nsex:%c\naddress:%s\n", a.num, a.name, a.sex, a.addr); 9
>嵌套结构体变量的访问:#include <stdio.h>#include <string.h>int mainO {struct Dateint year; int month; int day;1 :struct Student {int num; char name[20]:struct Date birthday;} a,b;strcpy(a. name, "Li Si");a.num = 1:版权所有@陈保留所有权利a.birthday.year = 2000;a.birthday.month = 12;b.birthday = a.birthday;return O;10
版权所有© 陈哲保留所有权利 ➢嵌套结构体变量的访问: #include <stdio.h > #include <string.h > int main() { struct Date { int year; int month; int day; }; struct Student { int num; char name[20]; struct Date birthday; } a, b; a.num = 1; strcpy(a.name, "Li Si"); a.birthday.year = 2000; a.birthday.month = 12; b.birthday = a.birthday; return 0; } 10