2017-05-28 55 views
-1

假设一个词在词典中有多个含义。实际上,在我的字典中,一个节点有5个含义。所以当我查找单词时,程序会打印2个含义以及其他3个100个字符长的垃圾值。C:避免链接列表中的垃圾值

如何避免它们被打印?

这里是我的代码:

struct node{ 
    char word[20]; 
    char meaning[5][100]; 
    struct node *next; 
}; 
void lookup(struct node *head, char *word) 
{ 
    int found = 0, i; 
    while(head != NULL) 
    { 
    if(strcmp(head->word, word) == 0) 
    { 
     found = 1; 
     printf("\n\t%s", word); 
     for(i = 0; i < 5; i++) printf("\n\t%s", head->meaning[i]); 
     printf("\n"); 
     break; 
    } 
    head = head->next; 
    } 
    if(found == 0) printf("\nWord not found in the dictionary!!"); 
} 
+0

未初始化结构字符串与NUL终止子,(猜测)。 – ThingyWotsit

回答

0

分配您的节点的元素用calloc或malloc的后做memset的,让你的节点的所有内存(或构件)充满0的默认。

struct node *node_element = (struct node *) calloc(1, sizeof(struct node)); 

然后通过检查长度打印的含义,

for(i = 0; i < 5; i++) { 
    if(strlen(head->meaning[i]) > 0) 
    printf("\n\t%s", head->meaning[i]); 
} 
+0

不为NULL - 使用零 - >'0'NULL具有不同的含义。看到“man calloc” – 0x0C4