0
Why do we have to use double pointers in stack structure?
We have a stack structure within one value and a pointer to the first element, then the function "popElement" takes as argument a double pointers to the stack, why can't we use just a simple pointer?
5 Respuestas
+ 1
OK, so you decide to build a stack in C.
To implement the 'pop' we need to return the value in the "last" node. We also need to free the memory of that node.
To get the value of the node we can do this easily with a pointer.
When free the node, if we just pass a pointer we get a copy of the pointer.
We can call free on this, but if make the pointer point to NULL, only this copy will point to NULL. ie the pointer in your list will point to the same area in memory even though its not allocated.
To fix this we can use a pointer to a pointer, then pass the address of the pointer. I think this is what you are asking about.
As Martin Taylor pointed out:
You could also pass an address of a stack structure, which would have a pointer to the first node.
Or if you implemented as a double linked list, you would have access to the whole list from any node.
+ 1
Ketan Lalcheta This implementation is closer to option 2, making a stack type.
You don't need to explicitly pass a pointer or reference to the stack as its a c++ class and the method is already associated with this stack.
0
meriem I am not sure whether I got your question or not. below is the link which has stack implementation using single pointer.
https://www.sololearn.com/learn/646/?ref=app
if this isn't your query, could you please elaborate your query for me ?
0
Jared Bird , I could not understand why double pointer is required as per your explanation and my shared code link.