#include<stdio.h>
struct stud
{
char name[20];
int mark;
int per;
char grad[5];
};
void main(){
int i,n;
printf("Enter number of students");
scanf("%d",&n);
struct stud s[n];
for(i=1;i<=n;i++)
{
printf("Enter name of student");
scanf("%d",s[i].name);
printf("Enter obtained marks");
scanf("%d",&s[i].mark);
s[i].per=s[i].mark/5;
}
for(i=1;i<=n;i++)
{
if(s[i].per>=80)
strcpy(s[i].grad,"A");
else if(s[i].per>=60)
strcpy(s[i].grad,"B");
else if(s[i].per>=50)
strcpy(s[i].grad,"C");
else if(s[i].per>=40)
strcpy(s[i].grad,"D");
else
strcpy(s[i].grad,"F");
}
for(i=1;i<=n;i++)
{
printf("&s",s[i].name);
printf("&d",s[i].mark);
printf("&d",s[i].per);
printf("&s",s[i].grad);
}
}
执行此代码时,它显示错误:
main.c: In function ‘main’:
main.c:25:10: warning: implicit declaration of function ‘strcpy’ [-Wimplicit-function-declaration]
strcpy(s[i].grad,"A");
^~~~~~
main.c:25:10: warning: incompatible implicit declaration of built-in function ‘strcpy’
main.c:25:10: note: include ‘<string.h>’ or provide a declaration of ‘strcpy’
main.c:27:11: warning: incompatible implicit declaration of built-in function ‘strcpy’
strcpy(s[i].grad,"B");
^~~~~~
main.c:27:11: note: include ‘<string.h>’ or provide a declaration of ‘strcpy’
main.c:29:11: warning: incompatible implicit declaration of built-in function ‘strcpy’
strcpy(s[i].grad,"C");
^~~~~~
main.c:29:11: note: include ‘<string.h>’ or provide a declaration of ‘strcpy’
main.c:31:10: warning: incompatible implicit declaration of built-in function ‘strcpy’
strcpy(s[i].grad,"D");
^~~~~~
main.c:31:10: note: include ‘<string.h>’ or provide a declaration of ‘strcpy’
main.c:33:10: warning: incompatible implicit declaration of built-in function ‘strcpy’
strcpy(s[i].grad,"F");
^~~~~~
main.c:33:10: note: include ‘<string.h>’ or provide a declaration of ‘strcpy’
这里的错误是什么?
答案 0 :(得分:1)
scanf("%d",s[i].name);
是未定义的行为。它将是"%s"
格式说明符。
而printf("%s",s[i].name)
不是&s
。
包含string.h
标头文件。
在获取输入时,数组索引也会超出范围。也是未定义的行为。数组索引从0
开始。所有循环都是for(i=0;i<=n-1;i++)
for(i=0;i<=n-1;i++)
{
printf("Enter name of student");
scanf("%s",s[i].name);
printf("Enter obtained marks");
scanf("%d",&s[i].mark);
s[i].per=s[i].mark/5;
}
另一个改变
for(i=1;i<=n;i++)
{
printf("%s",s[i].name);
printf("%d",s[i].mark);
printf("%d",s[i].per);
printf("%s",s[i].grad);
}