结构数组:
定义方法:
struct student students[50];
结构数组的每个元素都是结构变量,其使用方法如下:
结构数组名【下标】.结构成员名
此外,结构数组中的数组元素之间可以相互赋值。
学生成绩排序:
#include<stdio.h>
struct student
{
int num;
char name[10];
int computer,english,math;
double average;
} ;
int main(void)
{
int i,index,j,n;
struct student students[50],temp;
printf("input n:");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("input the informention of NO %d\n",i+1);
printf("input the student num:");
scanf("%d",&students[i].num );
printf("name:");
scanf("%s",students[i].name );
printf("computer,english and math:");
scanf("%d%d%d",&students[i].computer ,&students[i].english ,&students[i].math );
students[i].average =(students[i].computer +students[i].english +students[i].math )/3.0;
}
for(i=0;i<n-1;i++)
{
index=i;
for(j=i+1;j<n;j++)
if(students[index].average >students[j].average )
{
index=j;
}
temp=students[i];
students[i]=students[index];
students[index]=temp;
}
printf("num\t name\t average\n");
for(i=0;i<n;i++)
{
printf("%d\t%s\t%.2f\n",students[i].num ,students[i].name ,students[i].average );
}
return 0;
}
结构指针:
结构指针就是指向结构类型变量的指针。结构类型的数据往往由多个成员组成,结构指针的值实际上是结构变量的首地址,即第一个成员的地址。
struct student students[50];
p=&stu;
用指针访问结构变量:
(1):用*p访问结构成员
(*p).num=101;
其中的括号是必不可少的,因为”."的优先级高于“*”.若没有括号,其含义会发生变化。
(2)用指向运算符->访问指针指向的结构成员:
p->num=101;
其效果与(1)是一样的,但在访问指针指向的结构成员时我们更多使用此方法.
结构指针也可作为函数参数。:
则定义函数便可以通过结构指针p对结构数组的数据进行访问了。极大的提高了参数传递的效率。
修改学生信息:
#include<stdio.h>
struct student
{
int num;
char name[10];
int computer,english,math;
double average;
} ;
int update_score(struct student *p,int n,int num,int course,int score);
int main(void)
{
int i,index,j,n;
int num,course,score;
struct student students[50],temp;
printf("input n:");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("input the informention of NO %d\n",i+1);
printf("input the student num:");
scanf("%d",&students[i].num );
printf("name:");
scanf("%s",students[i].name );
printf("computer,english and math:");
scanf("%d%d%d",&students[i].computer ,&students[i].english ,&students[i].math );
}
printf("input the number of the students to be updated");
scanf("%d",&num);
printf("input the course:1.computer 2.english 3.math");
scanf("%d",&course);
printf("input the new score");
scanf("%d",&score);
j=update_score(students,n,num,course,score);
if(j=-1)
{
printf("no student");
}
else
{
printf("After update:\n");
printf("num\t math\t english\t computer\n");
printf("%d\t%d\t%d\t%d\n",students[j].num ,students[j].math ,students[j].english ,students[j].computer );
}
return 0;
}
int update_score(struct student *p,int n,int num,int course,int score)
{
int j,i;
for(i=0;i<n;i++,p++)
{
if(p->num ==num)break;
}
if(i<n)
{
switch(course)
{
case 1: p->computer =score;
break;
case 2: p->english =score;
break;
case 3: p->math = score;
break;
}
j=i;
}
else
{
j=-1;
}
return j;
}