demo:修改某个学生的成绩不利用指针直接在主函数内修改学生成绩的代码:
#include <stdio.h>#include <string.h>#define N 5struct student{char name[20];int score;}stu[N],temp;int main(void){int ch;//ch为'y'/'Y'表示继续修改学生成绩printf("请输入五个学生的姓名,成绩:\n");for(int i=0;i<N;i++) //录入五个学生的姓名和成绩scanf("%s %d",stu[i].name,&stu[i].score);do{printf("请输入要修改的学生的姓名:\n");scanf("%s",temp.name);for(int i=0;i<N;i++)if(strcmp(temp.name,stu[i].name)==0)//字符串相等{printf("请输入%s的成绩:\n",stu[i].name);scanf("%d",&stu[i].score);printf("修改成功:%s:%d\n",stu[i].name,stu[i].score);break;}else if(i==N-1)printf("不存在该学生\n");printf("是否还要继续修改学生成绩(Y/N):\n");getchar();//吸收换行符scanf("%c",&ch);}while(ch=='Y'||ch=='y');return 0;}
执行结果如下:
3.如果想要把修改成绩这一功能包装为函数,需要借助指针去修改结构体的变量的值
#include <stdio.h>#include <string.h>#define N 5struct student{char name[20];int score;}stu[N],temp;void alter_score(struct student *stu,struct student temp)//stu的数据需要修改,所以运用指针类型{for(int i=0;i<N;i++,stu++)if(strcmp(temp.name,stu->name)==0)//字符串相等{printf("请输入%s的成绩:\n",stu->name);scanf("%d",&stu[i].score);printf("修改成功:%s:%d\n",stu->name,stu->score);break;}else if(i==N-1)printf("不存在该学生\n");}int main(void){int ch;//ch为'y'/'Y'表示继续修改学生成绩struct student *p;printf("请输入五个学生的姓名,成绩:\n");for(int i=0;i<N;i++) //录入五个学生的姓名和成绩scanf("%s %d",stu[i].name,&stu[i].score);do{printf("请输入要修改的学生的姓名:\n");scanf("%s",temp.name);p=&stu;alter_score(p,temp);printf("是否还要继续修改学生成绩(Y/N):\n");getchar();//吸收换行符scanf("%c",&ch);}while(ch=='Y'||ch=='y');return 0;}//Joe 89//Mike 55//Lily 99//nike 77//sarch 65
结果如下:
3.总结:
注意区分结构体指针变量*stu的成员值用stu->name或者(*stu).name表示结构体变量stu表示成员值用stu.name即可另外,char str[10];scanf("%s",str);接收字符串无需取地址符号‘&’