Sup*_*ess 1 c struct pointers scanf segmentation-fault
#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;
}
Run Code Online (Sandbox Code Playgroud)
现在,我真的有点亏.在运行它时,它会询问产品的名称,将其打印出来,以便我知道它存储了它,然后询问库存量,它将崩溃并返回-1.
我不知道出了什么问题.我试着换出fgets用scanf,只是可以肯定的,但同样的事情发生.我猜我struct的设置错了,但我不知道怎么回事.它char可能是阵列吗?此外,无论我如何安排它,它始终是第二个输入.那么为什么第一个这么好呢?
谢谢你的帮助!
cod*_*ict 10
我能看到的一个快速错误就是缺失&了scanf.
scanf("%d", &product->stock);
^
scanf("%d", &product->price);
^
Run Code Online (Sandbox Code Playgroud)
编译器警告你这样的错误:
warning: format ‘%d’ expects type ‘int *’, but argument 2 has type ‘int’
Run Code Online (Sandbox Code Playgroud)
不要忽略编译器警告.