2017-02-22 51 views
-2

我需要C.利用嵌套鏈接列表Ç

struct subject     
{ 
char *subj[100]; 
char *tutor[100]; 
char *mark[10]; 
char *date[20]; 

struct subject* next2; 
}*head2; 

struct student    
{ 
char *name[20]; 
char *surname[20]; 
int num; 
struct subject *head2; 

struct student* next1; 
}*head1; 

創建鏈表裏面鏈表我有這兩種結構。我嘗試使用文件在循環中添加像這樣的新節點。

void newstudent(FILE *fp, char buffor[255], char buffor1[255]) 
{ 
struct student *temp1; 
temp1 = (struct student*) malloc(sizeof(struct student)); 
struct subject *temp2; 
temp2 = (struct subject*) malloc(sizeof(struct subject)); 
fscanf(fp, "%s", temp1->name); 
fscanf(fp, "%s", temp1->surname); 
fscanf(fp, "%d", &temp1->num); 
strcpy(temp2->subj, buffor); 
strcpy(temp2->tutor, buffor1); 
fscanf(fp, "%s", temp2->mark); 
fscanf(fp, "%s", temp2->date); 
temp1->next1 = NULL; 
head1 = temp1; 
temp2->next2 = NULL; 
head2 = temp2; 
} 

而當我只需要添加主題。

struct subject *temp2; 
temp2 = (struct subject*) malloc(sizeof(struct subject)); 
strcpy(temp2->subj, buffor); 
strcpy(temp2->tutor, buffor1); 
printf("%s %s\n",temp2->subj,temp2->tutor); 
fscanf(fp, "%s", temp2->mark); 
fscanf(fp, "%s", temp2->date); 
temp2->next2 = head2; 
head2 = temp2; 

我有問題,當我嘗試顯示「主題」列表中的元素。

while(link != NULL) 
{ 

    fprintf(output, "%s %s\n", link->name,link->surname); 
    fprintf(output, "Number: %d\n", link->num); 
    struct subject *link2 = head2; 
    while (link2 != NULL) 
    { 
     fprintf(output, "%s\n", link2->subj); 
    } 

    link = link->next1; 
} 

我認爲這是實現嵌套列表的問題。

+1

未定義的行爲嘉豪。打開編譯器警告,閱讀它們,修復它們,再試一次。 – EOF

+2

學生真的有20個名字指針和第二個名字指針的數組嗎?或者你打算'char name [20];'而不是'char * name [20];'?與其他結構類似。爲什麼哦爲什麼你沒有嘗試一個簡單的案例,並通過微小的可證明的步驟來構建代碼步驟? –

回答

1

循環:

while (link2 != NULL) 
{ 
    fprintf(output, "%s\n", link2->subj); 
} 

將是無限的,如果鏈接2不爲空。在循環內部必須是一個語句,它在某個時間點分配NULL,以使循環結束。