为什么在创建push函数时使用指向堆栈指针的指针? [英] Why use a pointer to a pointer to the stack when creating a push function?
问题描述
我在看一个实现堆栈的链接列表的教科书示例。我不明白为什么使用指针指向堆栈的指针是push操作所必需的。请参阅以下示例:
bool push(Element ** stack,void * data)
{
Element * elem = new Element;
if(!elem)return false;
elem-> data = data;
elem-> next = * stack;
* stack = elem;
return true;
}
如果任何人可以帮助澄清为什么push方法的第一个参数是一个指针到指针,我会非常感谢。
非常感谢您的帮助。
该函数需要修改Element指针的值,因此需要一个指向 指针的指针。
:一个函数需要一个指针的东西,当它需要修改那个东西。
在这种情况下,该东西是一个指针本身。因此,函数最终获取指向指针的指针。
I am looking at a textbook example of a linked list that implements a stack. I don't understand why using a pointer to a pointer to the stack is necessary for the push operation. See the following example:
bool push( Element **stack, void *data)
{
Element *elem = new Element;
if(!elem) return false;
elem->data = data;
elem->next = *stack;
*stack = elem;
return true;
}
If anyone can help clarify why the first parameter of the push method is a pointer to a pointer, I would greatly appreciate it. Thanks.
Amazing, thank you for all of the excellent help.
The function needs to modify the value of the Element pointer, so it needs a pointer to that pointer.
Put it another way: a function takes a pointer of something when it needs to modify that thing.
In this case, that something is a pointer itself. So the function ends up taking a pointer to a pointer.
这篇关于为什么在创建push函数时使用指向堆栈指针的指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!