【发布时间】:2016-12-27 04:32:15
【问题描述】:
我正在尝试学习 C 中的 struct。代码符合要求,但当我尝试输入一个值时,它会崩溃。我尝试了 int 成员,它有效。
typedef struct node{
char *productName;
int price;
struct node *next;
}node;
int main (){
node *head = (node*) malloc(sizeof(node));
printf("Enter a product name: ");
scanf("%s", &head->productName);
printf("Product entered:%s",head->productName);
//scanf("%d", &head->price); // this works
//printf("Price entered:%d",head->price);
}
【问题讨论】:
-
1.不要强制转换 malloc - 请参阅 here。 2.
prodeuctName指向什么? -
productName 没有分配内存来保存您在 scanf() 中获得的任何内容。