作者热门文章
- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我一直在编写一个程序,与我迄今为止处理的程序相比,该程序相当复杂。无论如何,在某些时候我应该编写一个函数来操作结构列表。我试图让这个问题尽可能简单,所以我写了一段非常简单的代码仅供引用。
事情是这样的:起初我从另一个函数中调用 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(¤t2, i); // recursively call by reference to the pointer
}
*current = (*current)->next; /* change the current pointer next pointer, CORRECTED as suggested by Azure */
return;
}
这里是一份非常好的学习指南文章列表:
关于c - 如何从递归中的函数编辑指向列表节点的指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8708265/
我是一名优秀的程序员,十分优秀!