我一直在努力了一段時間的特定作業功能,涉及到使用列表和動態分配內存到列表的第二維,並填充其元素,使用以下結構: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。通常我會選擇返回一個列表或使用雙指針作爲參數,但這些不是這個任務的選項。任何幫助/編程建議將不勝感激。
使鏈接像'new_node = malloc(sizeof(* new_node));/* set new_node */new_node-> next = list_holder; list_holder = new_node;'另外'list_holder'以NULL開頭。 – BLUEPIXY