2017-10-31 3 views
-1

私は、コースを追加しようとしている生徒のリンクリスト内のリンクリストを持っています。私がコースを追加しようとすると、彼らはお互いを上書きします。 最後のelse if()ブロックまでのすべてのもの(すべてのコース情報のコレクション)。それが間違っているところでは、新しいコースを2回目のループに挿入することです(else {} else {strcmp(arr [0]、 "}")== 0){} "リンクリストの上書きにノードを追加する

したがって、それは

struct course cour; 

それはcourがローカル変数であり、あなたが投稿コードの外へ出るとき(すなわち、もはや存在しない)スコープの外に行くことを意味します。

else if (strcmp(arr[0], " course") == 0) 
{ 
    // Start making a course 
    struct course cour; 
    while (fgets(str, sizeof(str), fp)) 
    { 
     str[strcspn(str, "\n")] = '\0'; // remove new line char from str 
     token = strtok(str, " "); 
     char *args[sizeof(str)]; 
     int i = 0; 
     while (token) // Tokenize that shit 
     { 
      arr[i] = token; 
      token = strtok(NULL, " "); 
      i++; 
     } 
     if (strcmp(arr[0], "#") == 0) 
     { 
      // Do nothing, it's a comment 
     } 
     else if (strcmp(arr[0], "  grade") == 0) 
     { 
      char *course_grade = arr[2]; 
      cour.grade = course_grade[0]; 
     } 
     else if (strcmp(arr[0], "  number") == 0) 
     { 
      char *course_num = arr[2]; 
      cour.number = atoi(course_num); 
     } 
     else if (strcmp(arr[0], " }") == 0) 
     { 
      // Done making the course, add to list 
      printf("We finished the course\n"); 
      if (stud.courses == NULL) // set as NULL when struct student stud is declared 
      { 
       // Since stud.courses == NULL, this must be the first course 
       cour.next = NULL; // make the end of the list NULL 
       stud.courses = &cour; 
      } 
      else 
      { 
       struct course *old = stud.courses->next; // old next course 
       stud.courses->next = &cour; // set the next course as the one we just made 
       cour.next = old; // replace the old next behind the new course 
      } 
      break; 
     } 
     else 
     { 
      printf("Nothing found :(\n"); 
     } 
    } 

答えて

1

は、私は1つの問題は、このラインだと思いますあなたがここでそうするように住所を保存することは悪い考えです:

stud.courses = &cour; 

ここ:

stud.courses->next = &cour; 

私はあなたの代わりに、動的変数が必要と思います。同様に:

struct course *cour = malloc(sizeof *cour); 

cour-> 

にすべての

cour. 

を変更するもう一つの問題は、これらの行

  struct course *old = stud.courses->next; // old next course 
      stud.courses->next = &cour; // set the next course as the one we just made 
      cour.next = old; // replace the old next behind the new course 

である彼らは次のようになります。

  cour->next = stud.courses; 
      stud.courses = cour; 
+0

オハイオ州私のゴッシュ、sooooたくさんありがとう! – Ethan

関連する問題