【问题标题】:what is wrong in making linked list from file从文件制作链表有什么问题
【发布时间】:2014-12-31 15:52:27
【问题描述】:

我想从这个文件中创建一个链表:

asd
aids
iwill

这是创建链表并返回其头部的函数:

firstNames* insertOfFirstNameF(FILE* file){
    char name[15];
    firstNames* head,*newPtr,*temp;
    while((head=(firstNames*)(malloc(sizeof(firstNames))))==NULL);
    fgets(name,12,file);
    head->name=name;
    head->linkPtr=NULL;
    temp=head;
    while(fgets(name,12,file)){
        while((newPtr=(firstNames*)(malloc(sizeof(firstNames))))==NULL);
        newPtr->name=name;
        newPtr->linkPtr=NULL;
        temp->linkPtr=newPtr;
        temp=newPtr;
    }
    return head;
}

struct firstNames 有两个字段,我在我的代码中都使用了它们。

这是主要功能:

int main(){
    FILE* file;
    file=fopen("firstnames.txt","r");
    firstNames* head=insertOfFirstNameF(file);
    fclose(file);
}

我解释它返回一个头,它的名称字段是“asd”(文件的第一个),但它的名称字段是“iwill”;

我的代码有什么问题?

【问题讨论】:

    标签: c file file-io linked-list


    【解决方案1】:

    name 是一个局部变量,函数返回后它的内容将不再存在,我建议快速修复

    head->name=strdup(name);
    

    newPtr->name=strdup(name);
    

    你应该记住free列表中每个节点的name成员,并且不要强制转换malloc在c中

    【讨论】:

    • 我不应该强制转换 malloc 吗?那我会遇到 IntelliSense 错误。
    猜你喜欢
    • 2015-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多