我正试图编写一个程序,从用户(从STDIN)获取行并将它们存储在一个链表中。
现在我只能获取一行并终止程序。如何更改代码以不断从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);
}
c
应该是int
,而不是char
。 - WhozCraiggetchar()
返回的内容,而这非常重要,尤其是在与EOF
进行比较时(正如您所做的那样)。 - WhozCraigstruct Node* new_node = malloc(sizeof(struct Node*));
(copied from the original source) is wrong. Must besizeof(struct Node)
orsizeof *new_node
- Ingo Leonhardt