Does top mean end or beginnning |
The point of a data structure is abstraction; that is, shouldn't matter whether or not, internally, the top of the stack is represented by the end or beginning of the underlying memory. As long as you are consistent, it shouldn't matter.
That being said, it looks like according to your code, you want the top index to be last valid index of your array, so the answer to your question would be
top = end.
st[top-1] would be the top of your stack.
st[0] is the bottom of your stack.
Also my program below shows an error about conversion from int* to int but i can't figure out what is wrong. |
The problem is the difference between your function prototype and your function definition.
Lines 3 & 4: you have
int as your first parameter
Lines 23 and 27: You have
int[] as your first parameter.
Change lines 3 and 4 to
1 2
|
void push(int[], int, int&);
void display(int[], int);
|
Your display function has a bug in it. (Hint: When do you use the
i value?)
You also have a fencepost error: After I enter 2 values, the for loop runs 3 times. Why is that? (Hint: What is the value of
top after you insert 2 items -- you probably should do top-1 as the start index.)
Last, since you pass
top as an int reference into
push, it would make sense if you also incremented
top inside of
push instead of after it.
___________________________________
In general, instead of asking us if a program is correct, you should know how to determine this yourself. You should develop simple "unit tests" to test the behavior of your code. Given an input [X] and output [Y], does the output match your
expected output [Z]?
https://ericlippert.com/2014/03/05/how-to-debug-small-programs/
Eric Lippert wrote: |
---|
If your program still has a bug, obtain a rubber duck. Or if a rubber duck is unavailable, get another computer science undergraduate, it’s much the same. Explain to the duck using simple words why each line of each method in your program is obviously correct. At some point you will be unable to do so, either because you don’t understand the method you wrote, or because it’s wrong, or both. Concentrate your efforts on that method; that’s probably where the bug is. Seriously, rubber duck debugging works. And as legendary programmer Raymond Chen points out in a comment below, if you can’t explain to the duck why you’re executing a particular statement, maybe that’s because you started programming before you had a plan of attack.
|