为什么在创建push函数时使用指向堆栈指针的指针? [英] Why use a pointer to a pointer to the stack when creating a push function?

查看:218
本文介绍了为什么在创建push函数时使用指向堆栈指针的指针?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在看一个实现堆栈的链接列表的教科书示例。我不明白为什么使用指针指向堆栈的指针是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屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆