[英]Program crashes when reading first data point
I want to see what student have the best mark in the class. 我想看看哪个学生在课堂上表现最好。 So I make this ,but i don't know where I am wrong
所以我做这个,但我不知道我在哪里错
struct Date {
char name[31];
float mark;
};
struct Date * Read(unsigned int n,struct Date *d){
int i;
for(i=0;i<n;i++){
getchar();
fgets(d[i].name, 31, stdin);
scanf("%f",d[i].mark);
}
return d;
}
int main(){
unsigned int n;
struct Date *d;
scanf("%u",&n);
d = (struct Date*) malloc(n*sizeof(struct Date));
d=Read(n,d);
free(date);
return 0;
}
after i read the mark the program crash. 在我读完标记后,程序崩溃了。 Can someone help me and explain what to change?
有人可以帮我解释一下要做什么吗? Thanks a lot.
非常感谢。
The crash is most likely due to this: 崩溃很可能是由于以下原因:
scanf("%f",d[i].mark);
You should pass the address as argument to read a float value. 您应该将地址作为参数传递,以读取浮点值。 It should be:
它应该是:
scanf("%f", &d[i].mark);
Technically, this is undefined behaviour. 从技术上讲,这是不确定的行为。 .
。
Compile with all warnings enabled. 编译并启用所有警告。 gcc warns even without any specific options:
gcc会发出警告,即使没有任何特定选项:
warning: format %f expects argument of type âfloat *â, but argument 2 has type double [-Wformat=]
警告:格式%f期望参数类型为“浮点*”,但参数2的类型为double [-Wformat =]
scanf("%f",d[i].mark);的scanf( “%F”,d [I] .mark);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.