我的 ArrayStack 在这里发生了什么?

What is going on with my ArrayStack here?

所以我一直在尝试实现一个 arrayStack,但我似乎遇到了弹出超过 100 个元素的问题。我的程序在达到一百时就停止工作。 push 和 pop 好像有问题,但是不太明白我的问题是什么。

#ifndef _ARRAYSTACK_1_HPP_
#define _ARRAYSTACK_1_HPP_

#include <stddef.h>
#include "StackADT.h"
#define DEFAULT_SIZE 50

template<class T>
class ArrayStack_1 : public StackADT<T> {

private: 
T *arrayStack; 
int index;
int maxSize;

public:
// a constructor for the arrayStack that creates and arrayStack of a given size
ArrayStack_1(int size = DEFAULT_SIZE) {
    maxSize = size;
    index = 0;
    arrayStack = new T[size];
}

public:

// a constructor for the arrayStack that creates and arrayStack of a given size
ArrayStack_1(int size = DEFAULT_SIZE) {
    maxSize = size;
    index = 0;
    arrayStack = new T[size];
}

//a destructor that deletes the arrayStack
~ArrayStack_1() {
    delete[] arrayStack;
}

bool Empty() {
    return index==0;
}

void Push(T& item = 0) {
    if (index<maxSize) {
        arrayStack[index]= item;
        index+=1;
    }else {
        T* tempArrayStack = arrayStack; //making a copy of the array stack
        maxSize+=1;
        arrayStack = new T[maxSize];

        for (int i=0; i<maxSize; i++){
            arrayStack[i]=tempArrayStack[i];
        }
        arrayStack[index]=item;
        index+=1;
        delete[] tempArrayStack;

    }
}

T Pop() {
        if(arrayStack[index]==0){
            return 0;
        }else {
            T element = arrayStack[index];
            index--;
            return element;
        }

   }
}

您可能只需要在 Pop 函数中将 arrayStack[index]==0 更改为 index == 0。否则,您可能会使用负索引访问 arrayStack,这是未定义的行为(可能是导致崩溃的原因)。

此外,当您重新分配堆栈时,您应该在重新分配之前增加堆栈大小。 IE。交换这些行:

    T* arrayStack = new T[maxSize];
    maxSize+=1;

此外,您没有将 arrayStack 的新值分配给您的成员变量 - 您在此代码中定义了一个新的局部变量。总的来说,这些行应该是:

    this->arrayStack = new T[++maxSize];

(请注意,您不必写 this->arrayStack,简单的 arrayStack = ... 就可以完成工作 - 它只是为了明确意图) 并且不要忘记 delete tempArrayStack,否则你会泄漏内存。

编辑 这些行也应该交换:

    index+=1;
    arrayStack[index]=item;

再次,您可以使用 ++ - 在本例中为后缀版本:

    arrayStack[index++] = item;

了解差异例如 here versus here

您真的应该单步执行这段代码,看看它在做什么。我不确定您如何成功完成 100 次迭代。

  1. 你在incrementing/decrementing的时候需要多加注意。有时在设置项目之前递增,有时在设置项目之后递增。

  2. 你推的是一个引用而不是一个指针(你的 arrayStack 应该是一个指针列表)。

  3. 您应该在遇到溢出情况时将大小加倍,以确保您不必在每次推送时都重新创建数组。

  4. 您有严重的内存泄漏,因为您在增加其大小时从未删除 arrayStack。

  5. 您正在分配一个局部变量,但没有对其进行任何操作。