Mohammad
Mohammad

Reputation: 362

what is wrong in making linked list from file

I want to make a linked list from this file:

asd
aids
iwill

This is the function that makes linked list and returns its head:

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 has two fields that I have used both of them in my code.

This is main function:

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

I expexted it returns a head that its name field is "asd" (first of the file) but its name field is "iwill" instead;

What is wrong with my code?

Upvotes: 0

Views: 64

Answers (1)

Iharob Al Asimi
Iharob Al Asimi

Reputation: 53016

name is a local variable and it's contents will no longer exists after the function returns, i would suggets a quick fix

head->name=strdup(name);

and

newPtr->name=strdup(name);

you should remember to free the name member of each node in the list, and Don't cast malloc in c.

Upvotes: 2

Related Questions