2014-11-21 2 views
0

저는 C로 된 "간단한"프로그램을 작업 중입니다. 여기서 C는 프로그램을 저장하는 영화처럼 작동하는 구조로 연결된 목록을 만듭니다. made, rating (1-5) 및 다음 노드에 대한 포인터가 포함됩니다. 우리는이 구조체에 아무것도 추가하거나 함수를 정의 할 수 없습니다.C에서 연결된 목록의 값을 비교할 때의 문제

우리는 (어떤 이유로) main() 본문에 전체 링크 목록을 작성해야하므로 문제에 대한 스파게티 계층을 추가합니다. 어쨌든,이 프로그램에서 우리는 사용자가 업데이트를 위해 'U'를 입력하거나 영화 검색을 위해 'S'를 입력하도록해야합니다. 업데이트는 예상했던대로 작동하며 제목, 연도, 등급을 입력합니다. 이것으로부터, 링크리스트의 에 노드를 삽입한다고 가정합니다.

우리의 검색은이 링크 된 목록을 반복해야하며 일치하는 것이 발견되면 영화, 제목 및 연도를 인쇄해야합니다.

내 코드의 업데이트 부분이 작동하지만 검색 기능이 작동하지 않는 것 같습니다. temp로 불리는 영화 구조체를 사용하고 있습니다. 머리말에서 시작하여 영화를 찾기 위해 목록을 반복합니다. printf를 통해 몇 가지 테스트를 실행 한 후에는 무엇을 입력하든 관계없이 temp가 null 노드 일뿐입니다.

malloc을 호출하는 것과 관련이 있다고 가정합니다. 또는 노드를 올바르게 할당하지 않는 것과 관련이 있습니까? 솔직히 잘 모르겠어요, 불행하게도, 실험실의 TA 잘못 D 중 무엇인지 몰랐다 :

#include <stdlib.h> 
#include <stdio.h> 
#include <string.h> 

struct movie_node { 
     char title[250]; 
     int year; 
     unsigned char rating; 
     struct movie_node *next; 
}; 

typedef struct movie_node movie; 

int main() { 

     // variables 
     int loop = 1; 
     movie *head = NULL; // represents first 
     movie *current; // represents the last node 
     movie *temp; // used for traversing the linked list 
     head = malloc(sizeof(movie)); 
     int amountOfMovies = 0; // increment after each addition 
     char choice; // either 'u' (update) or 's' (search) 
     // ask user for input 
     while(loop) { 

       printf("%d Movie(s) in the database. Update or search (U/S): ", amountOfMovies); 
       scanf(" %c", &choice); 
       /* CHOICE 1, UPDATE */ 
       if(choice == 'U') { 

         // case 1, head is null, we must create a new node 
         if(head == NULL) { 
           // get input 
           printf("Name of the movie: "); 
           scanf(" %[^\n]%*c", head->title); 
           printf("Year: "); 
      scanf("%d", &head->year); 
           printf("Rating: "); 
           scanf("%hhu", &head->rating); 
           head->next = NULL; 
           head = current; // set head to point to current 
         } else { 
           current = head; 
           // need to find where current is 
           while(current != NULL) { 
             current = current->next; 
           } // end while 
           // current is now at the null position, indicating empty node 
           current = malloc(sizeof(movie)); // allocate mem 
           // get user input 
           printf("Name of the movie: "); 
           scanf(" %[^\n]%*c", current->title); 
           printf("Year: "); 
           scanf("%d", &current->year); 
           printf("Rating: "); 
           scanf("%hhu", &current->rating); 
           current->next = NULL; 
         } // end else 
         // output movie 
         printf("Movie \"%s\" is added to the database.\n", current->title); 
         amountOfMovies++; // increment amount of movies in database 
       } else if(choice == 'S') { 
       /* CHOICE 2, SEARCH */ 
         // temp string 
         char tempTitle[250]; 
         // flag to let us know if we found something 
         bool found = false; 
         // temp linked list to traverse 
         temp = head; 
         temp = malloc(sizeof(movie)); 
         // ask user for input 
         printf("Name of movie: "); 
         scanf(" %[^\n]%*c", tempTitle); 
         printf("NAME OF MOVIE IN HEAD: %s\n", temp->title);    // test, take out later 
         while(temp != NULL) { 
           printf("NAME OF CURRENT MOVIE TO COMPARE TO: %s\n", temp->title); // test 
           if(strcmp(temp->title, tempTitle) == 0) { 
             // match 
             printf("Year: %d\n", temp->year); 
             printf("Rating: %hhu\n", temp->rating); 
             found = true; 
             break; 
           } else { // no match so far 
             temp = temp->next; 
             printf("HAVEN'T FOUND MATCH, NEXT TITLE TO CHECK IS: %s\n", temp->title); // test print 
             found = false; 
           } // end else 
         } // end while 
         if(found == false) { // no match confirmed 
           printf("Movie \"%s\" does not exist in the database.\n", tempTitle); 
         } 
       } else { // choice is invalid 
         loop = 0; // exit 
       } // end if-else 

     } // end while 
     // free all the nodes 

     return 0; 
} 

참고 : 여기에

내 코드는 아직 구현하지 않은 유일한 것입니다 기억을 풀어. 나는 그것을 어떻게 성취해야하는지 100 퍼센트 확신하지 못한다.

어떤 도움이 크게 감사합니다 ..

+0

시도를 해결합니다. 이렇게하면 코드를 읽고 디버그하기가 쉽습니다. – Shravan40

+0

당신의 코드는 다음을 포함합니다 :'if (head == NULL) {printf ("영화의 이름 :"); scanf ("% [^ \ n] % * c", head-> title);'null 포인터 (_bad 아이디어 ™ _)에 액세스하고 있음을 의미합니다. 입력을하기 위해서는 많은 코드가 필요합니다. 입력을 수행하는 함수를 작성하고 데이터를 읽을 변수 (구조)에 대한 포인터를 전달해야합니다.또한 사용자가 프로그램에 'EOF'(control-D 또는 control-Z)를 입력하여 코드를 강화해야합니다 (입력 작업 결과 테스트). –

+0

프로그램은'temp = head;'와'temp = malloc (sizeof (movie));'를 실행합니다. 이 논리는 무의미한가? – cshu

답변

0

문제는 malloc() 전화와 함께입니다. 먼저 수행

movie *head = NULL; 
// ... 
head = malloc(sizeof(movie)); 

이 머리가 더 이상 널 (null)입니다 당신은 당신이 원하는 방식으로 첫 번째 동영상을 삽입 할 수 없음을 의미합니다 - 그 malloc() 다른 곳으로 이동합니다.

둘째, 코드 몇 줄 아래에, 당신이 할 :

current = head; // <- this is OK 
// ... 
current = malloc(sizeof(movie)); // allocate mem <- this is NOT OK, for the same reason as before 

또한, 그런 영화의 제목을 읽을 수 있습니다 scanf("%249s", head->title).

어떻게 가야할지 알고 있으면 알려주세요.

코드의 문제 외에도 다른 문제가 있습니다. 실험실의 TA가 무엇이 잘못되었는지 전혀 알지 못 했으니입니다.

0

샘플은 각 작업에 대한 함수를 작성하는

movie *new_node(void){//aggregate the creation of a new node 
    movie *node = malloc(sizeof(*node));//error check omit 
    printf("Name of the movie: "); 
    scanf(" %249[^\n]%*c", node->title); 
    printf("Year: "); 
    scanf("%d", &node->year); 
    printf("Rating: "); 
    scanf("%hhu", &node->rating); 
    node->next = NULL; 
    return node; 
} 

int main() { 
    int loop = 1; 
    movie *head = NULL; 
    movie *current; 
    movie *temp; 
    //head = malloc(sizeof(movie));//"if(head == NULL) {" don't work 
    int amountOfMovies = 0; 
    char choice; 

    while(loop) { 
     printf("%d Movie(s) in the database. Update or search (U/S): ", amountOfMovies); 
     scanf(" %c", &choice); 

     if(choice == 'U') { 
      if(head == NULL) { 
       current = head = new_node();//need set to current 
      } else { 
       current = head; 
       while(current->next != NULL) {//"current != NULL" can't link 
        current = current->next; 
       } 
       current = current->next = new_node(); 
      } 
      printf("Movie \"%s\" is added to the database.\n", current->title); 
      amountOfMovies++; 
     } else if(choice == 'S') { 
      char tempTitle[250]; 
      bool found = false;//need <stdbool.h> 
      temp = head; 
      //temp = malloc(sizeof(movie));//Unnecessary 
      printf("Name of movie: "); 
      scanf(" %249[^\n]%*c", tempTitle); 
      //printf("NAME OF MOVIE IN HEAD: %s\n", temp->title);    
      while(temp != NULL) { 
       //printf("NAME OF CURRENT MOVIE TO COMPARE TO: %s\n", temp->title); 
       if(strcmp(temp->title, tempTitle) == 0) { 
        printf("Year: %d\n", temp->year); 
        printf("Rating: %hhu\n", temp->rating); 
        found = true; 
        break; 
       } else { 
        temp = temp->next; 
        printf("HAVEN'T FOUND MATCH, NEXT TITLE TO CHECK IS: %s\n", temp->title); 
        //found = false;//Unnecessary 
       } 
      } 
      if(found == false) { 
       printf("Movie \"%s\" does not exist in the database.\n", tempTitle); 
      } 
     } else { 
      loop = 0; 
     } 
    } 
    // free all the nodes 
    return 0; 
} 
관련 문제