gpt4 book ai didi

c - 在c中打印链表值时出现奇怪的值

转载 作者:行者123 更新时间:2023-11-30 16:39:19 25 4
gpt4 key购买 nike

我使用链接列表在 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 停止输入

最佳答案

我认为这是因为您实际上没有为该项目分配空间,您只是重复使用相同的缓冲区。 insert(&LinkedList, strdup(token));

您还在比较指针而不是字符串

if(当前->项目==目标)

if (strcmp(当前->项目,目标)==0)

尽管存在当前的错误,但它可能实际上会起作用!

关于c - 在c中打印链表值时出现奇怪的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47087235/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com