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