Frage

-Program given below adds a student node with id,marks and name from the information in INPUT FILE.

-It creates a linked list of these students by using addToList()

#include<stdio.h>
#define MAXLINE 10
struct student{
    int id;
    char *name;
    int marks;
    struct student *next;
    struct student *tail;
};

void addToList(int id,char *name,int marks,struct student *head){
    struct student *node=(struct student *)malloc(sizeof(struct student));
    node->id=id;
    node->name=name;
    node->marks=marks;
    node->next=NULL;
    head->tail->next=node;
    head->tail=node;
    printf("%d %s %d\n",head->id,head->name,head->marks);
}
int main(){
    FILE *fp=fopen("C:/Users/Johny/Desktop/test.txt","r");
    int id,marks;
    char f,name[MAXLINE];
    struct student *head;
    f=fscanf(fp,"%d %s %d",&id,name,&marks);
    if(f!=EOF){
        head=(struct student *)malloc(sizeof(struct student));
        head->id=id;
        head->marks=marks;
        head->name=name;
        head->next=NULL;
        head->tail=head;
    }
    printf("%d %s %d\n",head->id,head->name,head->marks);
    while((f=fscanf(fp,"%d %s %d",&id,name,&marks))!=EOF)
        addToList(id,name,marks,head);
    return 0;

INPUT FILE:

1 "J" 36
2 "O" 40
3 "H" 23
4 "N" 39
5 "Y" 78

CORRECT OUTPUT

1 "J" 36
1 "J" 36
1 "J" 36
1 "J" 36
1 "J" 36

OUTPUT CURRENTLY

1 "J" 36
1 "O" 36
1 "H" 36
1 "N" 36
1 "Y" 36

What is happening with name field of structure? How come only this is changing?Head pointer is pointing to the first node of linked lists.Expected output has to be correct output.

War es hilfreich?

Lösung

Bug is you are not copying but assigning the address of name to node->name. So all node's name field points to same string that is name that you have declared in main as as char name[MAXLINE];.

And because in add function, you are printing head->name that pointing to name, and the value in name is a string that is last read from file. Hence head->name print nothing but last string read from file and head->name print string j, o h....

To correct it you should allocate memory explicitly and strcpy(node->name, name) as follows.

node->name = malloc(strlen(name) + 1);  // allocate memory
strcpy(node->name, name);  // copy instead of assigning same address  
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top