我想学习C中的结构。代码符合罚款,当我尝试输入一个值,它崩溃。我尝试了一个int
成员,它的工作原理。输入值从scanf结构
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);
}
[请参阅此讨论关于为什么不在'C'中投射'malloc()'和家族的返回值。](http://stackoverflow.com/q/605845/2173917)。 –
1.不要投射malloc - 参见[这里](http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc)。 2.什么是'prodeuctName'指向? –
productName没有分配内存以保留您在scanf()中获得的任何内容。 –