简体   繁体   English

链接列表未正确链接

[英]Linked List not linking properly

This is just a snippet of my code. 这只是我的代码的一部分。 This function should create a linked list from a given file "dictionary.txt" which contains one word on each line, but I simply can't seem to get the links to work properly. 此功能应从给定的文件“ dictionary.txt”创建一个链接列表,该文件的每一行都包含一个单词,但是我似乎无法使链接正常工作。 When I run the code I get the first 2 entries properly (a,aa) but then it skips straight to the last entry (zyzzyvas) and a seg fault and it skips all other 80000 or so entries between. 当我运行代码时,我正确地获得了前2个条目(a,aa),但随后它直接跳到了最后一个条目(zyzzyvas)和段错误,并且跳过了其他所有80000个左右的条目。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct word {
    char entry[64];
    struct word *next;
}   WORD;

WORD *Dstart, *Dend, *curr;

WORD* makeDictionary() {

    FILE *fp;
    fp=fopen("dictionary.txt","r");

    fgets(Dstart->entry,63,fp);
    fgets(Dend->entry,63,fp);
    Dstart->next=Dend;
    int count=1;
    while(!feof(fp))
    {
        curr = (WORD *) malloc(sizeof(WORD));
        fgets(curr->entry,63,fp);
        Dend->next=curr;
        Dend=Dend->next;
        Dend->next=NULL;
        count++;
    }
    int i;
    curr=Dstart;
    for (i=1;i<=20;i++)    //Just to test if it's linking
    {
        printf("%s",curr->entry);
        curr=curr->next;
    }
}

int main {

    // curr = (WORD *) malloc(sizeof(WORD)); moved to the while loop
    Dstart = (WORD *) malloc(sizeof(WORD));
    Dend = (WORD *) malloc(sizeof(WORD));
    Dstart->next=NULL;
    Dend->next=NULL;

    makeDictionary();
    return(0);
}

Edit: Thank you Matt and interjay, moving the curr malloc into the while body fixed the problem I was having. 编辑:谢谢马特和interjay,将curr malloc移动到while正文中解决了我遇到的问题。 Fixed my code. 修正了我的代码。

You are only ever allocating three nodes (at program initialization), and overwriting one of them repeatedly. 您只分配了三个节点(在程序初始化时),然后重复覆盖其中一个。 You need to allocate a new node for each line in the file. 您需要为文件中的每一行分配一个新节点。 For example, you can move the line curr = malloc(sizeof(WORD)); 例如,您可以将行curr = malloc(sizeof(WORD)); to the beginning of the while loop body. while循环主体的开头。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM