gpt4 book ai didi

c - 如何从递归中的函数编辑指向列表节点的指针?

转载 作者:太空狗 更新时间:2023-10-29 17:24:30 25 4
gpt4 key购买 nike

我一直在编写一个程序,与我迄今为止处理的程序相比,该程序相当复杂。无论如何,在某些时候我应该编写一个函数来操作结构列表。我试图让这个问题尽可能简单,所以我写了一段非常简单的代码仅供引用。

事情是这样的:起初我从另一个函数中调用 testf,为它提供一个有效的 current 以及一个带有 a 的 i值为 0。这意味着 testf 在开始访问其余代码之前将调用自身约 100 次。这是所有生成的 testf 实例开始解析的时候。

 void testf(listnode *current, int *i) {
wordwagon *current2;

current2 = current;
if (*i < 100) {
*i = *i + 1;
current2 = current2->next;
testf(current2, i);
}


current = current->next;
return;
}

比方说,如果我有足够的连接列表节点供我使用,current = current->next; 是“last”testf 函数访问和编辑调用者的正确方法 current2 值(这是此函数的 current),还是我错得离谱?如果我是,那么从被调用函数内部更改调用函数的变量并确保它们不会在被调用函数返回后立即消失的方法是什么?我发现很难很好地掌握指针的工作原理。

很可能我遗漏了重要信息,或者我的问题问得不够清楚。如果是这种情况,请通知我,以便我可以根据您的需要进行编辑。

提前致谢。

最佳答案

您可以将指针传递给函数中的指针,并取消引用它以取回列表节点指针,这是之后代码的样子(未经编译测试):

void testf(listnode **current, int *i) {  // accept pointer to listnode pointer
wordwagon *current2;

current2 = *current; // retreive pointer value by dereferece
if (*i < 100) {
*i = *i + 1;
current2 = current2->next;
testf(&current2, i); // recursively call by reference to the pointer
}

*current = (*current)->next; /* change the current pointer next pointer, CORRECTED as suggested by Azure */
return;
}

这里是一份非常好的学习指南文章列表:

a) http://cslibrary.stanford.edu/102/PointersAndMemory.pdf

b) http://cslibrary.stanford.edu/103/LinkedListBasics.pdf

关于c - 如何从递归中的函数编辑指向列表节点的指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8708265/

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