【发布时间】:2017-11-03 01:47:59
【问题描述】:
我使用链表在 C 中创建了一个应用程序,该应用程序从标准输入中逐行获取数据,并将每个单词输入到链表中,最后打印所有这些单词而没有任何重复,所以我制作了这个代码
//linked list
typedef struct NODE Node;
struct NODE{
char *item;
Node *next;
};
//insert function
bool insert(Node** head_ref, char *new_string)
{
/* allocate node */
struct NODE* new_node = (struct NODE*) malloc(sizeof(struct NODE));
/* put in the data */
new_node->item = new_string;
/* link the old list off the new node */
new_node->next = (*head_ref);
/* move the head to point to the new node */
(*head_ref) = new_node;
return true;
}
// tells us whether or not the given string is in the list
bool search(struct NODE *head, char *target)
{
struct NODE *current = head;
while (current != NULL)
{
if (current->item == target)
return true;
current = current->next;
}
return false;
}
// declare of the linked list
Node *LinkedList = NULL;
//function used to read the stander input from the user
void loadFile()
{
#define LINE_SIZE 256
char input[LINE_SIZE];
char *token = NULL;
while ( fgets( input, LINE_SIZE, stdin ) )
{
// parse the data into separate elements
token = strtok( input, " \t\n" );
while ( token )
{
if (!search(LinkedList, token)) {
insert(&LinkedList, token);
//puts("insert");
}
else {
//printf("Not insert\n");
}
token = strtok( NULL, " \t\n" );
}
}
}
这个函数打印列表中的所有单词
void Print(Node* head)
{
Node *current = head;
while (current != NULL)
{
printf("%s\n", current->item);
current = current->next;
}
}
当我在最后打印单词时,它给了我主要的奇怪字符
int main()
{
loadFile();
Print(LinkedList);
return 0;
}
我在 windows 上使用 cntrl + Z 停止输入
【问题讨论】:
-
预期输出和实际输出的示例是什么?
-
关于:
struct NODE { char *item; Node *next; };最好将Node *next;替换为struct NODE *next;,并将typedef放在结构体定义后 -
在调用任何堆分配函数(malloc、calloc、realloc)时 1) 始终检查 (!=NULL) 返回值以确保操作成功。 2)返回的类型是
void*,可以赋值给任何指针,强制转换只会使代码混乱,使其更难理解、调试等。 -
在函数中:
insert(),这个语句:new_node->item = new_string;导致所有item指针指向输入缓冲区的开始(所以它们都指向同一个东西)他们每个人都需要指向唯一的字符串。建议:new_node->item = strdup(new_string); if( !new_node->item ) { // then strdup failed, handle error, cleanup, callexit()` }` -
发布的代码无法将分配的内存返回到堆。 (这通常是通过调用
free()来完成对从调用malloc(),calloc()` 的调用返回的每个指针。)不进行调用的结果是内存泄漏。
标签: c pointers linked-list token c-strings