我正在尝试编写一个程序,该程序从用户(来自 STDIN)获取行并将它们存储在链接列表中。

现在我只得到一行并终止程序。
如何更改代码以继续从标准输入获取行?

另外,如果有人能告诉我我是否正在按应有的方式分配和释放内存,那将非常有帮助。

谢谢。

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

int BUFF_SIZE = 128;

struct Node {
    char* data;
    struct Node* next;
};

struct Node* head = NULL;
struct Node* tail = NULL;

void free_list(struct Node* head)
{
    if (head != NULL)
    {
        free_list(head->next);
        free(head);
    }
}

int main()
{
    int curr_size = 0;

    char* pStr = malloc(BUFF_SIZE);
    curr_size = BUFF_SIZE;

    printf("%s", "please print multiple lines\n");
    if (pStr != NULL)
    {
        char c;
        int i = 0;

        while ((c = getchar()) != '\n' && c != EOF)
        {
            pStr[i++] = c;

            if (i == curr_size)
            {
                curr_size = i + BUFF_SIZE;
                pStr = realloc(pStr, curr_size);
                if (pStr == NULL) return;
            }
        }
        pStr[i] = '\0';

        struct Node* new_node = malloc(sizeof(struct Node*));
        char* new_data = malloc(sizeof(pStr));
        new_data = pStr;
        new_node->data = new_data;

        if (head == NULL)
        {
            head = new_node;
            tail = new_node;
        }

        else
        {
            tail->next = new_node;
        }
    }

    free_list(head);
}

最佳答案

几个问题:

  • 现在你在收到 \n 时终止阅读。
    if (pStr == NULL) return; //error
    
    int c;
    int i = 0;
    
    while ((c = getchar()) != EOF)
    {
       /*New word, insert into linked list*/
       if (c == '\n'){
           pStr[i] = '\0';
    
           struct Node* new_node = malloc(sizeof(*new_node));
           char* new_data = malloc(i+1);
           strcpy(new_data, pStr);
           new_node->data = new_data;
    
           if (head == NULL)
           {
                head = new_node;
                tail = new_node;
           }
           else
           {
                tail->next = new_node;
                tail = new_node;
           }
           i = 0; //Reset the index
       }
       else {
    
           pStr[i++] = c;
           if (i == curr_size)
           {
               curr_size = i + BUFF_SIZE;
               pStr = realloc(pStr, curr_size);
               if (pStr == NULL) return;
           }
       }
    }
    
  • 内存泄漏,节点 data 将始终指向 pStr 的最新内容。
    char* new_data = malloc(sizeof(pStr));
    new_data = pStr;   //Memory leak here
    new_node->data = new_data;
    

    将其更改为
    char* new_data = malloc(i+1);
    strcpy(new_data, pStr);
    new_node->data = new_data;
    

  • 将每个节点插入列表后,您需要更新 tail
     else
     {
         tail->next = new_node;
     }
    


     else
    {
        tail->next = new_node;
        tail = new_node;
     }
    
  • 关于c - 如何从标准输入读取多行并将其存储在链表中,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56442478/

    10-11 23:09
    查看更多