2017-03-19 56 views
0

我一直在努力了一段時間的特定作業功能,涉及到使用列表和動態分配內存到列表的第二維,並填充其元素,使用以下結構:2d鏈接列表內存不攜帶

13 typedef struct BookIds{ 
    14  int id; 
    15  struct BookIds* next; 
    16 }bookIds; 
    18 typedef struct Student{ 
    //Unimportant struct elements 
    23  bookIds* wishlist; 
    24  struct Student* next; 
    25 }student; 

,然後調用

void addWishlist(student* head, char* wishListfile) { 
//cannot modify parameters or return type 
191  FILE* f = fopen(wishListfile, "r"); 
192  student* current = head; 
193  int i; 
194  int* wish = malloc(sizeof(int) * 4); 
195  while (current != NULL) { 
196   current->wishlist = malloc(sizeof(bookIds)); 
197   fscanf(f, "%d %d %d %d", (wish), (wish+1), (wish+2), (wish+3)); 
198   for (i = 0; i < 4; i++) { 
199    current->wishlist->id = *(wish+i); 
200    current->wishlist->next = malloc(sizeof(bookIds)) 
201    current->wishlist = current->wishlist->next; 
202   } 
203   current = current->next; 
204  } 
205  free(wish); 
206  fclose(f); 
207 } 

的問題是,該函數調用後,第二陣列列表失去其存儲器(所有元素都爲NULL),因爲它是一個通由VAL。通常我會選擇返回一個列表或使用雙指針作爲參數,但這些不是這個任務的選項。任何幫助/編程建議將不勝感激。

+0

使鏈接像'new_node = malloc(sizeof(* new_node));/* set new_node */new_node-> next = list_holder; list_holder = new_node;'另外'list_holder'以NULL開頭。 – BLUEPIXY

回答

1

問題是,在函數調用後,第二個數組列表失去了內存(所有元素都是NULL),因爲它是val傳遞。

沒有這不是問題在這裏,因爲傳遞給函數的參數都沒有改變函數內部。

相反,我認爲你的問題是在這裏:

198   for (i = 0; i < 4; i++) { 
199    current->wishlist->id = *(wish+i); 
200    current->wishlist->next = malloc(sizeof(bookIds)) 
201    current->wishlist = current->wishlist->next; 
202   } 

看來你要wishlist包含4個元素,但在線條201更改current->wishlist指向鏈中的最後一個元素。所以你最終只有一個未初始化的元素。

您可以通過元素的簡單的繪圖和指針看到:

enter image description here

正如你所看到的,你必須在執行線201

當丟失後的第一個元素該函數完成,它看起來像這樣:

enter image description here

你甲肝e丟失了除最後一個元素之外的所有元素(其中btw未初始化)。

因此,您需要重寫上述行,以便您不會更改行201中的current->wishlist.還要記住將最後的next指針設置爲NULL。

 fscanf(f, "%d %d %d %d", (wish), (wish+1), (wish+2), (wish+3)); 
    bookIds* p; 
    for (i = 0; i < 4; i++) { 
      if (i == 0) { 
       current->wishlist = malloc(sizeof(bookIds)); 
       p = current->wishlist; 
      } else { 
       p->next = malloc(sizeof(bookIds)); 
       p = p->next; 
      } 
      p->id = = *(wish+i); 
      p->next = NULL; 
     } 

BTW:

也許你會喜歡的東西取代線196-202您還應該添加檢查mallocfscanf取得成功。

+0

你是一個救星;感謝你也包括一個解釋,該解釋與我在gdb和輸出中獲得的內容相匹配。但如果你不介意我問,爲什麼代碼''current-> wishlist = current-> wishlist-> next;''指向最後一個元素而不是下一個元素? –