91结控体 16 9.12结构体变量的定义与初始化 【例96】编写一个统计选票的程序。 struct candidate { char name20;/name为候选人姓名* int count; /coun为候选人得票数* 3 list[ invalid,0,t Zhao",0 Qian",03, "Sun",0},{"L",0},{Zhou",0}; 2021/2/21
2021/2/21 16 9.1 结构体 9.1.2 结构体变量的定义与初始化 【例9.6】编写一个统计选票的程序。 struct candidate { char name[20]; /* name为候选人姓名 */ int count; /* count为候选人得票数 */ } list[ ]={{"invalid",0},{"Zhao",0},{"Qian",0}, {"Sun",0},{"Li",0},{"Zhou",0}};
91结控体 9.12结构体变量的定义与初始化 main i int i, n; printf( Enter votein") scant("%d",&n);/输入所投候选人编号,编号从1开始 while(n!=-1) /当输入编号为-1时,表示投票结束 fif(m>=1&&n<=5) istn] count+;/有效票,则相应候选人计票成员加1* else &printf(invalid); list o]. count-++;}无效票,lst0的计票成员加 scanf("%d",&n);/输入所投候选人编号 2021/2/21
2021/2/21 17 9.1 结构体 9.1.2 结构体变量的定义与初始化 main( ) { int i,n; printf("Enter vote\n"); scanf("%d",&n); /* 输入所投候选人编号,编号从1开始 */ while (n!=-1) /* 当输入编号为-1时,表示投票结束 */ { if (n>=1 && n<=5) list[n].count++; /* 有效票,则相应候选人计票成员加1 */ else { printf("invalid\n"); list[0].count++; } /* 无效票,list[0]的计票成员加1 */ scanf("%d",&n); /* 输入所投候选人编号 */ }
91结控体 18 9.12结构体变量的定义与初始化 for〔i=1;i=5;i++) printf("os: /dn", list(i name, listi count) printf(oos: %d\n",list O- name, list(0]. count); 2021/2/21
2021/2/21 18 9.1 结构体 9.1.2 结构体变量的定义与初始化 for (i=1; i<=5; i++) printf("%s:%d\n",list[i].name,list[i].count); printf("%s:%d\n",list[0].name,list[0].count); }
91结控体 19 913结构体的指针 1.结构体指针变量的定义 结构体指针变量定义的一般形式: struct结构体名指针变量名; 例如: p是指向 struct student结 struct student *p; 构体变量的指针变量 struct date f int year, month, day;*q; 2021/2/21
2021/2/21 19 9.1 结构体 1. 结构体指针变量的定义 结构体指针变量定义的一般形式: struct 结构体名 *指针变量名; struct date { int year, month, day;}*q; 例如: struct student *p; p是指向struct student结 构体变量的指针变量 9.1.3 结构体的指针
91结控体 20 913结构体的指针 2.结构体成员的三种引用形式 struct date f int year, month, day; d,*p=&d; ●用结构体变量名的引用形式:“->”是指向结构体成 d year d month d day 员运算符,优先级为一级 用结构体指针变量的引用形式 (p).year p)month (p)day p->year p->month p->day p=&ayear 2021/2/21
2021/2/21 20 9.1 结构体 9.1.3 结构体的指针 2. 结构体成员的三种引用形式 ⚫ 用结构体变量名的引用形式: d.year d.month d.day struct date { int year, month, day;}d, *p=&d; ⚫ 用结构体指针变量的引用形式: (*p).year (*p).month (*p).day p->year p->month p->day “->”是指向结构体成 员运算符,优先级为一级 p=&d.year ×