Why use a pointer to a pointer to the stack when c

2019-07-25 17:56发布

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.

7条回答
ゆ 、 Hurt°
2楼-- · 2019-07-25 19:02

You'll have to update a pointer.

A list is nothing but a pointer to an Element. So you may rewrite this to

bool push(List* stack, void* data);

Not you see that, in case you wouldn't use the double pointer, your actual declaration was

bool push(List stack, void* data);

which wouldn't change the original list at all.

But alternately,

bool push(Element* &stack, ...)

is OK too since it allows you updates.

查看更多
登录 后发表回答