我正在尝试使我的链表工作在最简单的级别。我想添加一个新的节点(变量wordNode)到我定义的链表(wordList)。在我的主要C文件中,我创建了一个新列表(createWordList),并在inputLine中添加了一个节点,其中包含单词“Hello”。为什么修改一个不相关的变量会导致我的链接列表发生变化?
问题是,当我尝试打印我的列表头部的单词时,将打印对输入行所做的任何更改。例如,此处打印的不是“Hello”,而是打印“Go”。我无法理解这是如何实现的,因为输入行与哈希表完全无关;单词“Go”不应该影响哈希表中的值吗?以下是主要功能的代码。
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中的指针传递,所以你如何解决这个问题?我尝试在'addWordNode'函数中将'strcpy'放入一个新数组中,但这并没有帮助。如果您必须传递一个将继续被修改的数组,那么标准做法是什么? –
“我试图在addWordNode函数中对一个新数组执行strcpy,但这并没有帮助”。这是一个合理的事情要做,如果正确完成,应该工作。具体来说,如果你已经正确分配了内存。所以请准确显示你做了什么。 – kaylum