gpt4 book ai didi

c - 为什么修改一个不相关的变量会导致我的链表发生变化?

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

我正在尝试使我的链接列表在最简单的级别上工作。我想向我定义的链表(wordList)添加一个新节点(变量wordNode)。在我的主 C 文件中,我创建了一个新列表 (createWordList),并向其中添加了一个节点,其中包含 inputLine 中的单词“Hello”。

问题是,当我尝试打印列表头部的单词时,将打印对输入行所做的任何更改。例如,此处不打印“Hello” ,打印“Go”。我无法理解这是怎么可能的,因为输入行完全与哈希表无关; “Go”这个词不应该影响哈希表中的值,对吧?下面是main函数的代码。

struct wordList* hashTable;
hashTable = createWordList();

char inputLine [20];

// set input line to Hello
strcpy (inputLine, "Hello");

// add Hello as the head node to the linked list
addWordNode (hashTable, inputLine);

// set input line to Go
strcpy (inputLine, "Go");

// print the head of the list. this is currently printing Go, instead of Hello.
if (hashTable->head != NULL) {
printf ("%s\n", i, hashTable->head->word);
}

以下是 createWordList() 函数的代码:

struct wordList* createWordList() {
struct wordList* list = malloc(sizeof(struct wordList));
list->head = NULL;
return list;
}

对于 addWordNode() 函数:

void addWordNode(struct wordList *list, char * word) {
struct wordNode* currentNode;
struct wordNode* newNode = malloc (sizeof(struct wordNode));
newNode -> word = word;
newNode -> docFrequency = 1;
newNode -> next = NULL;

// I've only included the first case, because that is what is setting the head value.

if (list->head == NULL) {
list->head = newNode;
return;
}

很抱歉要求直接调试,但我已经为此花费了几个小时。是否存在我不理解的字符串或字符串操作的较大行为?或者那里有一个简单的错误?

最佳答案

“因为输入行完全不链接到哈希表”?恰恰相反,在 addWordNode 函数中,您将新节点直接链接到本地​​ inputLine 数组,该数组是您传递给 addWordNode 函数的指针外。 “取消链接”是您忘记做的事情。 – AnT

关于c - 为什么修改一个不相关的变量会导致我的链表发生变化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40902927/

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