清华大学出版社 TSINGHUA UNIVERSITY PRESS §11.2定义结构体类型先声明一个 struct date 例如: struct date/“声明类型,它代表“日期 int num ”,包括3个成员: char name20];日)、ya(y month(月)、day char sex 然后在声明 struct int age student类型时,将成 birthday addr Num name sex age Month day year 图11-3
§11.2 定义结构体类型变量的方法 例如:struct date /*声明一个结构体类型*/ int num; char name[20]; char sex; int age; float score; struct date birthday; /*birthday是struct date类型*/ char addr[30]; }student1,student2; 先声明一个struct date 类型,它代表“日期 ”,包括3个成员: month(月)、day( 日)、year(年)。 然后在声明struct student类型时,将成 员birthday指定为 struct date类型。 图11-3 birthday addr Num name sex age Month day year
清华大学出版社 TSINGHUA UNIVERSITY PRESS §11.3结构体变量的引用 在定义了结构体变量以后,当然可以 引用这个变量。但应遵守以下规则: (1)不能将一个结构体变量作为一个整体进行输 入和输出。 例如:已定义 student1和 student2为结构体变 量并且它们已有值。 printf("%d, %S, %C, %d, %f, %\n", studen
§11.3结构体变量的引用 ◼ 在定义了结构体变量以后,当然可以 引用这个变量。但应遵守以下规则: (1)不能将一个结构体变量作为一个整体进行输 入和输出。 例如: 已定义student1和student2为结构体变 量并且它们已有值。 printf(″%d,%s,%c,%d,%f,%\n″,student1);
清华大学出版社 TSINGHUA UNIVERSITY PRESS §11.3结构体变量的引用 引用结构体变量中成员的方式为 结构体变量名.成员名 例如, student1num表示 student1变量中的 num成员即 student1的num(学号)项。 可以对变量的成员赋值,例如 student1num=10010;3是成员(分量) 运算符,它在所有的运算符中优先级最高, 因此可以把 student1num作为一个整体 来看待。上面赋值语句的作用是将整数 10010赋给 student1变量中的成员num
§11.3结构体变量的引用 引用结构体变量中成员的方式为 结构体变量名.成员名 例如, student1.num表示student1变量中的 num成员,即student1的num(学号)项。 可 以 对 变 量 的 成 员 赋 值 , 例 如 :student1.num=10010;“.”是成员(分量) 运算符,它在所有的运算符中优先级最高, 因此可以把student1.num作为一个整体 来看待。上面赋值语句的作用是将整数 10010赋给student1变量中的成员num
清华大学出版社 TSINGHUA UNIVERSITY PRESS §11.3结构体变量的引用 (2如果成员本身又属注意: 若干个成员运算符不能用 级的成员。只能对 值或存取以及运算。 student. birthday 例如:对上面定义的结构体来访间 Student变 这样访问各成员:量中的成员 studentnum birthday,因为 student1 birthday. mor birthday本身是 个结构体变量
§11.3结构体变量的引用 (2) 如果成员本身又属一个结构体类型,则要用 若干个成员运算符,一级一级地找到最低的 一级的成员。只能对最低级的成员进行赋 值或存取以及运算。 例如: 对上面定义的结构体变量student1, 可以 这样访问各成员: student1.num student1.birthday.month 注意: 不能用 student1.birthday 来访问student1变 量中的成员 birthday,因为 birthday本身是一 个结构体变量
清华大学出版社 TSINGHUA UNIVERSITY PRESS §11.3结构体变量的引用 (3)对结构体变量的成员可 行各种运算(根据其浅由于“,”运算符的 运算 优先级最高,因此s 例如 t d en t 1, a ge++是对stu student2score=studen d e n t 1. age sum= student1 score+s进行自加运算,而不 studentIage++ 是先对age进行自 ++student2 age 加运算
§11.3结构体变量的引用 (3) 对结构体变量的成员可以像普通变量一样进 行各种运算(根据其类型决定可以进行的 运算)。 例如: student2.score=student1.score; sum=student1.score+student2.score; student1.age++; ++student2.age; 由于“.”运算符的 优先级最高,因此s tudent1.a ge++是对stu dent1.age 进行自加运算,而不 是先对age进行自 加运算