c++ - Stack with push and pop functions not working -
this program.
#include<iostream> #include<string> using namespace std; struct stack { int inf; stack* link; } *start, *p; void push(stack*, stack*, int); void pop(stack*, stack*); int main() { int s = 0; string thing; cin >> thing; while (thing != "end") { if (thing == "push") { push(start, p, s); } if (thing == "pop") { pop(start, p); } cin >> thing; } return 0; } void push(stack *start, stack *p, int s) { cin >> s; p = start; start = new stack; start->inf = s; start->link = p; cout << "pushed " << start->inf << endl; } void pop(stack *start, stack *p) { cout << "popped " << start->inf; p = start; start = start->link; delete p; } it's simple program allow me push , pop items , stack, reason pop() won't work. if add if(start) before pop skips it, making me think stack somehow becomes null after push completed. works until reaches cout << "popped " << start->inf; line, when crashes (no error message) again makes me think stack becomes null before reaches pop(). suggestions?
first, both of function's signature weird:
void push(stack *start, stack *p, int s) void pop(stack *start, stack *p) assuming start points top of stack, should discard p. should local variable function, not parameter.
second, let's see push implementation:
p = start; start = new stack; start->inf = s; start->link = p; this 1 looks good. missed start declared pointer stack, , changing pointer inside function, value parameter instead of reference. current signature, can change start points to, not start itself. can either declare pointer pointer stack, , change body accordingly (you need double dereference assigning inf , link) or use reference parameter adding & before parameter name. same case applies pop function.
Comments
Post a Comment