【发布时间】:2019-07-20 20:24:05
【问题描述】:
我正在尝试在 C++ 中实现动态堆栈。 我在类堆栈中有 3 个成员 1.cap是容量。 2.top-指向栈顶 3. arr- 指向整数的指针。
在类构造函数中,我将内存分配给堆栈(malloc)。 稍后在 meminc() 中,我试图重新分配内存。
我已经编写了一个函数 meminc() 来重新分配内存,但是我得到了这个无效的旧大小错误。
如果您让我知道这段代码有什么问题,将会很有帮助。我也会感谢给我的任何建议。 谢谢。
#include <iostream>
using namespace std;
#define MAXSIZE 5
class stack {
int cap;
int top;
int *arr;
public:
stack();
bool push(int x);
bool full();
bool pop();
bool empty();
bool meminc();
};
stack::stack()
{
cap = MAXSIZE;
arr = (int *)malloc(sizeof(int)*MAXSIZE);
top = -1;
}
bool stack::meminc()
{
cap = 2 * cap;
cout << cap << endl;
this->arr = (int *)realloc(arr, sizeof(int)*cap);
return(arr ? true : false);
}
bool stack::push(int x)
{
if (full())
{
bool x = meminc();
if (x)
cout << "Memory increased" << endl;
else
return false;
}
arr[top++] = x;
return true;
}
bool stack::full()
{
return(top == MAXSIZE - 1 ? true : false);
}
bool stack::pop()
{
if (empty())
return false;
else
{
top--;
return true;
}
}
bool stack::empty()
{
return(top == -1 ? true : false);
}
int main()
{
stack s;
char y = 'y';
int choice, x;
bool check;
while (y == 'y' || y == 'Y')
{
cout << " 1.push\n 2.pop\n" << endl;
cin >> choice;
switch (choice)
{
case 1: cout << "Enter data?" << endl;
cin >> x;
check = s.push(x);
cout << (check ? " push complete\n" : " push failed\n");
break;
case 2: check = s.pop();
cout << (check ? " pop complete\n" : " pop failed\n");
break;
default: cout << "ERROR";
}
}
}
【问题讨论】:
-
您的堆栈需要 iostream,这很有趣。
标签: c++ memory dynamic malloc realloc