511结构体的引出及使用 结构体的定义及使用 struct student 1、结构体类型的定义 用户定义{ int num 的标识符 har name 10 i struct结构体类型名 char sex; 关数据类型成员名 int age: int score 键数据类型成员名2;成员表列, char instit20 字 数据类型成员名n; 注意不要忘了分号 注意:定义了结构体类型,仅仅是定义了数据的组织形式,创立了 种数据类型。但并不会为这种结构体类型分配内存空间 只有定义了结构体变量,才会为变量分配空间
struct student { int num ; char name[10] ; char sex; int age; int score ; char institute[20] }; 二、结构体的定义及使用 5.1.1 结构体的引出及使用 注意: 定义了结构体类型,仅仅是定义了数据的组织形式,创立了 一种数据类型。但并不会为这种结构体类型分配内存空间 只有定义了结构体变量,才会为变量分配空间。 注意不要忘了分号 成员表列 1、结构体类型的定义: struct 结构体类型名 { 数据类型 成员名1; 数据类型 成员名2; : : 数据类型 成员名n; } ; 关 键 字 用户定义 的标识符
511结构体的引出及使用 2、定义结构体变量的方法 name 1)先定义结构体类型,再定义变量 age struct student stl 结构体 2 char namel101;类型定义」name int age i 结构体 age int sI 2 st2 变量定义 S2 struct student stI, st2 i 内存中结构体变量占有一片连续的存储单元,其占用的字节数 可用 sizeof运算符算出: printf(odin, sizeof(struct student)) printf(se odn”, sizeof(st1)) 结构体变量s和st2各自都需要16个字节的存储空间
5.1.1 结构体的引出及使用 2、 定义结构体变量的方法 (1) 先定义结构体类型, 再定义变量 struct student { char name[10] ; int age ; int s1 , s2 ; } ; struct student st1 , st2 ; st1 st2 name age s1 s2 name age s1 s2 ➢内存中结构体变量占有一片连续的存储单元, 其占用的字节数 可用sizeof 运算符算出: printf(“%d\n” , sizeof(struct student) ) ; printf(“%d\n” , sizeof(st1) ) ; ➢结构体变量st1和st2各自都需要16个字节的存储空间 结构体 类型定义 结构体 变量定义
511结构体的引出及使用 2、定义结构体变量的方法 (2)定义结构体类型同时定义变量 struct student i char name 10; int age int s1. s2 3 stl,st2 定义结构体变量 (3)直接定义结构体变量 struct 注意这里没有结构体类型名 char namel101;这种方式有时使用并不方便 int age i 因此不建议大家采用 int sI, s2 i 3 stI, st2 i
5.1.1 结构体的引出及使用 2、 定义结构体变量的方法 (2) 定义结构体类型同时定义变量 struct student { char name[10] ; int age ; int s1 , s2 ; } st1 , st2 ; (3) 直接定义结构体变量 struct { char name[10] ; int age ; int s1 , s2 ; } st1 , st2 ; 注意:这里没有结构体类型名 这种方式有时使用并不方便 因此不建议大家采用 定义结构体变量
511结构体的引出及使用 结构体类型可以嵌套定义 例: struct date 或: struct stud int year i i char name 101; int month struct date int day i int year i int month struct stud int day i char name; 3 birthday i struct date birthday int s1, S2 int sI. s2
5.1.1 结构体的引出及使用 例: struct date { int year ; int month ; int day ; } ; struct stud { char name[10] ; struct date birthday ; int s1 , s2 ; } ; ➢结构体类型可以嵌套定义 或 : struct stud { char name[10] ; struct date { int year ; int month ; int day ; } birthday ; int s1 , s2 ; } ;