91结构体 16 912结构体变量的定义与初始化 例96】编写一个统计选票的程序。 struct candidate char name20;/name为候选人姓名* int count /coun为候选人得票数 Blist[invalid,0,t Zhao",0,t Qian", 03, "Sum",0},{"Li",0},{"Zhou",0}; 2021-2-24
2021-2-24 16 【例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结构体 17 912结构体变量的定义与初始化 man i int i, n; p rin itf( "Enter vote); scanf("%od"',&n);/输入所投候选人编号,编号从1开始* while(n!=. /当输入编号为-1时,表示投票结束 if(n>=1&&n<=5) istn] count;/有效票,则相应候选人计票成员加1* else printf( invalid\n); list0 Lcount;}无效票,it0的计票成员加1* scant("%d",&n);/输入所投候选人编号* 2021-2-24
2021-2-24 17 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 912结构体变量的定义与初始化 for (i=l; i<=5; 1++) printf(oos: %odn",isti name, listi count) printf(oos: dn",list(O]- name, list[O]. count); 2021-2-24
2021-2-24 18 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); }
9]结构体 19 913结构体的指针 1.结构体指针变量的定义 结构体指针变量定义的一般形式: struct结构体名指针变量名; 例如: p是指向 struct student结 struct student*p; 构体变量的指针变量 struct date f int year, month, day; *q 2021-2-24
2021-2-24 19 p是指向struct student结 构体变量的指针变量
9]结构体 20 913结构体的指针 2.结构体成员的三种引用形式 struct date f int year, month, day; d,p=&d; ●用结构体变量名的引用形式“->”是指向结构体成员 d year d month dday 运算符,优先级为一级 ●用结构体指针变量的引用形式: (p)year (p)month (p,day p>year p>month p>day & p-aasyear 2021-2-24
2021-2-24 20 “->”是指向结构体成员 运算符,优先级为一级 p=&×d.year