2016-12-27 78 views
1

我想学习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); 

} 
+0

[请参阅此讨论关于为什么不在'C'中投射'malloc()'和家族的返回值。](http://stackoverflow.com/q/605845/2173917)。 –

+0

1.不要投射malloc - 参见[这里](http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc)。 2.什么是'prodeuctName'指向? –

+0

productName没有分配内存以保留您在scanf()中获得的任何内容。 –

回答

2

的第一个问题,%sscanf()需要一个char *的说法,你正在传递一个char **

这就是说,即使经过更正(除去&),head->productName是未初始化的,它不指向有效的存储器位置。访问未初始化的内存调用undefined behavior

你需要使指针指向有效内存才可以读取或写入它。

最后,在使用返回的指针之前,您应该始终检查malloc()的成功。

结合所有的人,像

node *head = malloc(sizeof *head); 
if (head) { 
    head->productName = malloc(32); //some arbitary size 
    if (head->productName) { 
     printf("Enter a product name: "); 
     scanf("%31s", head->productName); 
     printf("Product entered:%s",head->productName); 
    } 
} 

应该做的工作。


注意:一般建议,不要忘记free()的内存分配函数返回的指针,以避免任何可能的内存泄漏,因为你的代码变得更加壮大。

+1

最后但并非最不重要。不要忘记释放你分配的内存 – bansi

+0

@bansi那么,这个特殊情况不会有任何区别,仍然是一个有效的点。 :) –

+0

在'如果'中写入所有内容不是一种好的写作风格,最好只是测试并在'if'中失败。只是说。 –

1

也许,你需要把它写是这样的:

/*Following code is not tested - Just a sample*/ 
typedef struct node{ 
    char *productName; 
    int price; 
    struct node *next; 
}node; 

int main(){ 
    node *head = (node*) malloc(sizeof(node)); 
    if(head == NULL) 
    /*fail*/ 
    printf("Size of product name:"); 
    scanf("%d",&size); 
    head->productName = malloc(size); 
    if(head->productName == NULL) { 
     /*fail*/ 
    } 
    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);*/ 

    /*Do stuff with node here*/ 
    free(head->productName); 
    free(head); 
    return 0; 
} 
+0

'if(head-> productName == NULL){ /* fail */ } .... scanf(“%s”,head-> productName);''whole' if's thing is nothingless then。假设你正在尝试写一个MCVE。 –