[英]C Programming Struct
#include<stdio.h>
#include<string.h>
struct s {
char ch[20];
float a;
};
int main()
{
struct s p[10];
int i;
for(i=0;i<10;i++)
{
scanf("%s%f",p[i].ch,p[i].a);
}
}
What is wrong with this code? 此代码有什么问题?
Its giving runtime error. 它给运行时错误。
What's the problem? 有什么问题?
Most of the errors come from this line. 大多数错误来自此行。
scanf("%s%f",p[i].ch,p[i].a);
You should use the address of p[i].a
, and also restrict the numbers of chars to write in p[i].ch
. 您应该使用p[i].a
的地址,并限制要写入p[i].ch
的字符数。
scanf( "%19s%f", p[i].ch, &p[i].a );
I haven't touched C code for a while but shouldn't it be something like 我已经有一段时间没有接触过C代码了,但是不应该像
scanf("%s%f",p[i].ch,&(p[i].a));
(You have to give the memory address of the variables to the scanf
function.) (您必须将变量的内存地址提供给scanf
函数。)
I think the problem is in the p[i].a
parameter; 我认为问题出在p[i].a
参数中; use &p[i].a
instead. 使用&p[i].a
代替。
At the line: 在此行:
scanf("%s%f", p[i].ch, p[i].a);
You are using p[i].a
as a float*
(pointer), while it's a float
. 您正在将p[i].a
用作float*
(指针),而它是float
。 You're invoking undefined behavior. 您正在调用未定义的行为。 You probably wanted to do it like this: 您可能想要这样做:
scanf("%s%f", p[i].ch, &p[i].a);
Change your code like this: 像这样更改代码:
#include <stdio.h>
#include <string.h>
struct s {
char ch[20];
float a;
};
int main(){
struct s p[10];
int i;
for(i=0;i<10;i++){
scanf("%s%f",p[i].ch, &p[i].a);
}
}
Note that variable a
is a float
type; 请注意,变量a
是float
类型; you need to pass its memory address when using scanf
. 使用scanf
时,您需要传递其内存地址。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.