C 程序以 -1 (0xFFFFFFFF) 终止,似乎没有原因?
#include <stdio.h>
typedef struct pduct {char name[20];
int price;
int stock;} PRODUCT;
void init(PRODUCT * product)
{
printf("What is the name of the product: ");
fgets(product->name, 20, stdin);
printf("DEBUG: Did it get written...: %s", product->name);
printf("What is the current stock of the item: ");
scanf("%d", product->stock);
printf("What is the price of the new item: ");
scanf("%d", product->price);
}
int main()
{
PRODUCT products[5];
init(products);
return 0;
}
现在,我真的有点不知所措。运行此程序后,它将询问产品名称,将其打印出来,以便我知道它存储了它,然后询问库存数量,此时它将崩溃并返回 -1。
我不知道出了什么问题。我尝试用 scanf
替换 fgets
,只是为了确定,但同样的事情发生了。我猜我的 struct
设置错误,但我不知道如何设置。也许是 char 数组?而且,无论我如何排列它们,它始终是第二个输入。那么为什么第一个效果这么好呢?
感谢您的帮助!
#include <stdio.h>
typedef struct pduct {char name[20];
int price;
int stock;} PRODUCT;
void init(PRODUCT * product)
{
printf("What is the name of the product: ");
fgets(product->name, 20, stdin);
printf("DEBUG: Did it get written...: %s", product->name);
printf("What is the current stock of the item: ");
scanf("%d", product->stock);
printf("What is the price of the new item: ");
scanf("%d", product->price);
}
int main()
{
PRODUCT products[5];
init(products);
return 0;
}
Now, I'm at a bit of a loss, really. Upon running this, it will ask for the name of the product, print it out so I know it stored it, then ask for the stock amount, where it will crash and return -1.
I have no idea what's going wrong. I've tried swapping out fgets
with scanf
, just to be sure, but the same thing happens. I'm guessing my struct
is set up wrong, but I don't know how. Is it the char
array maybe? Also, it's always the second input, no matter how I arrange them. So why does the first work so well?
Thanks for any help!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我发现的一个快速错误是
scanf
中缺少&
。编译器会警告您此类错误:
不要忽略编译器警告。
One quick bug I can see is missing
&
inscanf
.The compiler warns you on such mistakes:
Don't ignore compiler warnings.
您需要传递
product->stock
的地址。那是:You need to pass the address of
product->stock
. That is:scanf 获取一个指向存储结果的位置的指针。在本例中,您使用 stock 的当前(未初始化)值作为写入 scanf 结果的地址。您需要说
scanf("%d", &product->stock)
等。scanf takes a pointer to where you store the result. In this case, you're using the current (uninitialized) value of stock as the address of where to write the result of the scanf. You need to say
scanf("%d", &product->stock)
, etc.