簡體   English   中英

嘗試將新節點插入鏈表時,程序崩潰。 為什么?

[英]Program crashes when trying to insert new nodes to linked list. Why?

因此,我正在將文件中的所有單詞讀到鏈接列表的數組中。 對於字母表的每個字母,我都有單獨的鏈接列表。

結構如下:

struct WORD {
    char* word;
    int noOfUse;
    struct WORD* next;
};

和數組:

struct WORD* dictionary[26];

然后循環讀取所有單詞:

do {
    fscanf(fp, "%s", buffer);
    printf("%s\n", buffer);
    dictionary[buffer[0]-'a'] = insertWord(buffer, dictionary[buffer[0]-'a']);
} while (!feof(fp));

和功能:

struct WORD* insertWord (char buffer[30], struct WORD* node){
if (node == NULL){
    node = (struct WORD*) malloc (sizeof(struct WORD));
    node->word = (char*) malloc (strlen(buffer)+1);
    strcpy(node->word, buffer);
    node->next = NULL;
}
else {
    node->next = insertWord(buffer, node->next);
}
return node;
}

我看不到我在為她做錯什么,但是程序運行后立即崩潰。 我是否想到達我不想到達的地方?

第一個struct WORD* dictionary[26]; 這可以用垃圾初始化,您可能應該將26個指針設置為NULL,

else {
  node->next = insertWord(buffer, node);
}

如果節點!= NULL則執行此操作,然后將其再次傳遞給insertWord函數,然后再次將節點!= NULL傳遞給您,然后再次啟動此函數...,這是無限遞歸。

還請記住有關大寫字母的信息。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM