结构体数组在函数之间传递数据
结构体数组作为函数参数在函数之间传递数据时,要求形参和实参是相同结构体类型声
明的数组,进行函数调用时,实参将数组名中存放的数组首地址传递给形参数组名。这样,实参数组名和形参名代表的是同一个结构体数组,因此在被调函数中对数组元素结构体变量的值进行修改后,回到主调函数通过实参数组名访问数组时,可以发现这个改变。
【例】选举投票程序。设有3个候选人参加选举,参加投票的人数为n,每个人只能投一票,从键盘输入人数n和每个投票人选的候选人名,统计并输出每个候选人的得票数。要求最后输出各候选人的得票情况时,按票数由高到低排列,票数相同时按姓名从小到大排列。
【思路分析】这是一个数组排序的问题,下面定义一个函数sort解决该问题,采用冒泡排序算法。
源代码如下
#include<stdio.h>
#include<string.h>
struct candicate //定义候选人的结构体类型
{
char name[]; //姓名
int count; //得票数
};
void sort(struct candicate c[]);
int main()
{
struct candicate cand[]={{"zhang",},{"li",},{"wang",}};
int n,i,j;
char name[];
printf("请输入投票人数:");
scanf("%d",&n);
printf("输入全部[%d]个投票人选举的候选人名:\n",n);
for(i=;i<=n;i++)
{
printf("第[%d]个投票人选举的人名:",i);
scanf("%s",name);
for(j=;j<;j++)
if(strcmp(cand[j].name,name)==)
{
cand[j].count++;
}
}
printf("候选人得票情况如下:\n");
sort(cand);
for(i=;i<;i++)
{
printf("%s:%d\n",cand[i].name,cand[i].count);
}
return ;
}
void sort(struct candicate c[])
{
int i,j;
struct candicate tmp;
for(i=;i<;i++)
{
for(j=;j<-i;j++)
{
if((c[j].count<c[j+].count)||(c[j].count==c[j+].count&&strcmp(c[j].name,c[j+].name)>))
{
tmp=c[j];
c[j]=c[j+];
c[j+]=tmp;
}
}
}
}
程序运行结果: