2014-01-25 44 views
1

- 下面給出的程序使用INPUT FILE中的信息添加了一個帶有id,標記和名稱的學生節點。結構中的指針奇怪的結果

- 它通過使用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; 

輸入文件:

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

正確的輸出

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

輸出CURRENTLY

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

結構的名稱字段發生了什麼?爲什麼只有這個變化呢?頭指針指向鏈表的第一個節點。期望的輸出必須是正確的輸出。

回答

0

錯誤是你不復制但分配地址namenode->name。因此,所有節點的名稱字段都指向您在主要聲明的name相同的字符串,如char name[MAXLINE];

而且因爲在添加功能中,您正在打印指向namehead->name,並且name中的值是最後一次從文件中讀取的字符串。因此head->name打印只是從文件和head->name打印字符串j,請閱讀最後一個字符串oh ....

要糾正它,你應該明確將和strcpy(node->name, name)分配內存。

node->name = malloc(strlen(name) + 1); // allocate memory 
strcpy(node->name, name); // copy instead of assigning same address