Understanding stack array implementation (C)
I completely understand what a stack is supposed to do (last in, first out). It's just one part of the stack that gets me confused.
typedef struct dynArrStruct
{
char *location; //element
int length; //max size
int currSize; //top
}dynArr;
dynArr a; //declared in main
//sorry this is an assignment and I try to refrain from posting my full code
//on here b/c of potential cheaters
I use this code as my stack.
Basically my program is supposed to find balanced characters: '{', '(','<', '[' and their closing counter parts.
In a nutshell, everytime I find an opening brace, I push it onto the stack. I keep pushing it onto the stack until I find a closing brace and as soon as I find a closing brace I need to pop the stack.
What I'm getting confused is with the variable char* location.
Let's say my string is "()"
In GDB:
If I read in '(' I push it onto the stack.. and if I read in ')' I pop it.
When I do: p a->location it prints out "()"
I'm just wondering am I supposed to be deleting "()" from the value of a->location everytime I pop a stack or is popping the stack irrelevant to a->location?
In other words should it print out "" after it has been popped?
I apologize ahead of time if this question doesn't make sense
Since you haven't posted your code it's hard to be sure, but I suspect you are confusing a pointer (eg char * location) with the contents it is pointing to. A pointer currently pointing to a string "()" will print out as () in gdb, but the character pointed to (top of stack) would be just '('.
It will be easier to be more specific if you post at least part of your code.
Yes, after you pop an element from the stack, it should no longer be accessible on the stack. The size of the stack, representing the number of accessible elements, should also decrease by one. The difference between accessing the top-value and popping the top value is one of the reasons why the C++ STL (I know you're working in C, but this is just for an example) provides two different functions for popping and accessing the top value in a std::stack
object. The std::stack::top
method allows you to actually access the element on the top of the stack, while the std::stack::pop
method removes the element by "popping" it off the top. If you are going to go with a single pop
method though, then that method should both return a copy of the value that was on the top of the stack while also removing the internal representation of that value from the stack data-structure.
下一篇: 了解堆栈数组实现(C)