Creating a singly linked list in C

后端 未结 3 1379
攒了一身酷
攒了一身酷 2021-01-13 00:58

I\'m trying to create a singly linked list from an input text file for an assignment. I\'m trying to do it a little bit at a time so I know my code is not complete. I trie

相关标签:
3条回答
  • 2021-01-13 01:17

    root has an undefined value, so it won't initialize. The second line of CreateList should be

    LIST *root = NULL;
    

    Also, further down there is allocation apparently for the details of the item, but a) the code fails to capture the allocation and save it anywhere, and b) the size of the allocation should be strSize, not the length of the variable itself. There are several ways to fix it, but the most straightforward would be:

    newList->str = (char *)malloc(strSize);
    if (newList->str == NULL)
    
    0 讨论(0)
  • 2021-01-13 01:27

    You shouldn't be incrementing head after head = head->next in the for loop. PrintList will return NULL every time since the loop wont stop until head is NULL. Why do you need to return the head of the list you just passed to the function anyway?

    Edit:

    LIST *current = head;
    while (current != NULL) {
        printf("%s    %d", current->str, current->count);
        current = current->next;
    }
    
    0 讨论(0)
  • 2021-01-13 01:29

    The second malloc allocates memory but its return value is not assigned to anything, so that allocated memory is lost.

    newList is allocated but not initialized, so using a memcpy to copy memory to newList->str will fail since newList->str points to nothing. Probably you wanted the result of the second malloc to be assigned to newList->str, but you forgot it.

    0 讨论(0)
提交回复
热议问题