2010-02-22 2 views
6

할당을 위해 입력 텍스트 파일에서 단독 연결 목록을 만들려고합니다. 한 번에 조금씩 해보려하고있어 코드가 완전하지 않다는 것을 알고 있습니다. 나는 헤드 포인터를 만들고 그 값을 인쇄 해 보았고 작동하도록 할 수는 없었지만 그 이유는 잘 모르겠습니다. 구조체, 작성 목록 및 인쇄 목록 함수를 포함했습니다. 나는 그 부분이 작동하기 때문에 열린 파일을 포함시키지 않았다.C에서 단일 연결 목록 만들기

typedef struct List 
{ 
    struct List *next; /* pointer to the next list node */ 
    char *str;   /* pointer to the string represented */ 
    int count;   /* # of occurrences of this string */ 
} LIST; 

LIST *CreateList(FILE *fp) 
{ 
    char input[LINE_LEN]; 
    LIST *root;    /* contains root of list    */ 
    size_t strSize;   
    LIST *newList;   /* used to allocate new list members */ 

    while (fscanf(fp, BUFFMT"s", input) != EOF) { 

     strSize = strlen(input) + 1; 

     /* create root node if no current root node */ 
     if (root == NULL) { 
      if ((newList = (LIST *)malloc(sizeof(LIST))) == NULL) { 
       printf("Out of memory..."); 
       exit(EXIT_FAILURE); 
      } 
      if ((char *)malloc(sizeof(strSize)) == NULL) { 
       printf("Not enough memory for %s", input); 
       exit(EXIT_FAILURE); 
      } 
       memcpy(newList->str, input, strSize); /*copy string */ 
       newList->count = START_COUNT; 
       newList->next = NULL; 
       root = newList; 
     } 
    } 
     return root; 
} 

/* Prints sinly linked list and returns head pointer */ 
LIST *PrintList(const LIST *head) 
{ 
    int count; 

    for (count = 1; head != NULL; head = head->next, head++) { 
     printf("%s %d", head->str, head->count); 
    }      
    return head;  /* does this actually return the start of head ptr, b/c I want to 
          return the start of the head ptr. */ 
} 
+1

'PrintList'에'head ++ '을 넣고 싶지 않다면,'head = head-> next'는 이미 포인터를 증가시킵니다. –

+1

두 번 묻습니까 ..? http://stackoverflow.com/questions/2309618/single-linked-lists-in-c – lorenzog

답변

2

root은 초기화되지 않습니다. CreateList의 두 번째 줄이 분명히 항목의 세부 사항에 대한 할당이지만) 코드가 할당을 캡처 어디서나 저장하는 데 실패, 그리고 b)는 크기가 더 아래로, 또한

LIST *root = NULL; 

해야한다 할당은 변수 자체의 길이가 아닌 strSize이어야합니다. 이 그것을 해결하는 방법은 여러 가지가 있지만 가장 간단한은 다음과 같습니다 당신은 for 루프에서 head = head->next 후 머리를 증가해서는 안

newList->str = (char *)malloc(strSize); 
if (newList->str == NULL) 
1

. PrintList는 head가 NULL이 될 때까지 루프가 멈추지 않으므로 매번 NULL을 반환합니다. 어쨌든 방금 함수에 전달한 목록의 머리를 왜 반환해야합니까?

편집 :

LIST *current = head; 
while (current != NULL) { 
    printf("%s %d", current->str, current->count); 
    current = current->next; 
} 
+0

내 교수가 원하는 것. 그리고 const char * 매개 변수는 루프를 반복하는 방법에 대해 혼란스러워했습니다. – Crystal

+0

현재 노드에 대한 포인터를 만들고 머리글로 초기화해야합니다. 다시 돌려 줄 때까지 머리를 다시 만지지 마십시오. –

1

두 번째의 malloc은 메모리 할당하지만 할당 된 메모리가 손실 될 수 있도록 반환 값은, 아무것도 할당되지 않습니다.

newList가 할당되었지만 초기화되지 않았으므로 memList를 사용하여 newList-> str에 메모리를 복사하면 newList-> str이 아무 것도 가리 키지 않으므로 실패합니다. 아마도 두 번째 malloc의 결과가 newList-> str에 할당되기를 원했지만 잊었을 것입니다.