简体   繁体   中英

Stack implementation using array C++

I am trying to implement some of the methods of the class "stack". For the push() method I am trying to duplicate the capacity of the array if the top of the stack equals the capacity. The top is the item of the next slot. I was doing this by creating a new array with double the capacity of the original array and then copying the content over. All the other methods I implemented (empty(), pop(), top()) seem to be working fine but the push function prints random values for the first 4 items of the stack for some reason if the stack has more than 10 elements (The capacity had to be increased). Why is this problem happening?

#include <iostream>
using namespace std;

class stack
{
    public:
        stack();
        bool empty();
        void pop();
        void push(int x);
        int &topElem();
    
    private:
        int *buffer;
        int top;                          // Top element of stack
        int capacity = 10;                // Capacity of array

};

stack::stack()
{
    int *val = new int[capacity];
    buffer = val;
    top = 0;
}

bool stack::empty()
{
    if(top == 0)
        return true;
    else
        return false;
}

void stack::push(int x)
{
    if(top == capacity)
    {
        int *newArray = new int[capacity * 2];
        for(int i = 0; i < capacity; i++)
        {
            newArray[i] = buffer[i];
            //cout << "newArray[" << i << "]: " << newArray[i] << endl;
        }
        buffer = newArray;
        delete[] newArray;
        newArray = NULL;
    }
    buffer[top] = x;
    top++;
}

void stack::pop()
{
    if(!empty())
    {
        top--;
    }
    else
        cout << "Stack is empty!" << endl;
}

int& stack::topElem()
{
    return buffer[top - 1];
}

int main()
{
    stack plates;
    
    for (int i = 0; i < 20; i++)  // Add 20 elements to the stack
    {
        plates.push(i);
    }

    while (!plates.empty())
    {
        cout << plates.topElem() << endl;      // Prints the elemtents of the stack
        plates.pop();                          // Pops the last element of the stack
    }
    return 0;
}

// Output 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 393 -1250224288 393 -1250206816

buffer = newArray;
delete[] newArray;

this doesn't do what you expect. It points buffer to the new array, leaking the old one, then deleting the memory the buffer is pointing to.

You probably want something like:

delete[] buffer; // free the old buffer
buffer = newArray; // point it to the newly allocated memory

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM