如何在递归中编辑函数中指向列表节点的指针?
与我迄今为止处理的程序相比,我一直在编写一个相当复杂的程序。无论如何,在某些时候我应该编写一个操作结构列表的函数。我试图让这个问题尽可能简单,所以我写下了一段非常简单的代码仅供参考。
事情是这样的:首先,我从另一个函数调用 testf
,为其提供有效的 current
以及值为 0 的 i
这意味着 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;
}
假设我有足够的连接列表节点可供使用,那么“last”testf 函数访问和编辑调用者的 的正确方法是
值(这是该函数的current = current->next;
current2current
),还是我错了? 如果是,如何从被调用函数内部更改调用函数的变量,并确保它们不会在被调用函数返回后立即消失?我发现很难很好地掌握指针的工作原理。
我很可能遗漏了重要信息或者我没有足够清楚地提出我的问题。如果是这种情况,请通知我,以便我可以根据您的需要进行编辑。
提前致谢。
I have been writing a program that is quite complex compared to what I have dealt with until now. Anyways at some point I am supposed to write a function that will manipulate a struct list. I'm trying to make this question as simple as possible so I wrote down a pretty simple piece of code just for reference.
Here is the thing: at first I call testf
from another function providing it with a valid current
as well as an i
with a value of 0. This means that testf will call itself about 100 times before it starts accessing the rest of the code. This is when all the generated instances of testf
will start getting resolved.
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;
}
If, let's say, I have enough connected list nodes at my disposal, is current = current->next;
the correct way for the "last" testf function to access and edit the caller's current2
value (which is this function's current
), or am I horribly wrong?
If I am, what is the way to make changes to the caller function's variables from inside the called function and be sure they won't go away as soon as the called function returns? I find it kind of hard to get a good grasp on how pointers work.
It is very likely that I have left out important information or that I haven't asked my question clearly enough. Please inform me if that is the case so I can edit in whatever you need.
Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以将指针传递给函数中的指针,并取消引用它以返回 listnode 指针,这是之后代码的样子(未测试编译):
这里是学习指针的非常好的文章列表:
a) http://cslibrary.stanford.edu/102/PointersAndMemory.pdf
b) http://cslibrary.stanford.edu/103/LinkedListBasics.pdf
You can pass pointer to a pointer in your function, and derefrence it to get a listnode pointer back , here is how the code will look like after that ( not tested for compilation ) :
Here is a list of really good articles for learning pointers :
a) http://cslibrary.stanford.edu/102/PointersAndMemory.pdf
b) http://cslibrary.stanford.edu/103/LinkedListBasics.pdf