使用 memcpy 将动态数组的内容复制到另一个动态数组上会产生运行时错误
Using memcpy to copy the content of a dynamic array onto another produces a runtime error
所以我正在尝试创建一个具有动态大小的堆栈,这意味着堆栈的容量将根据需要动态变化。这个概念在我的脑海中完美无缺,创建一个函数名称memoryManagement(int i)
,该函数名称通过一个名为usedCapacity
的变量获取当前存储在堆栈中的数据的大小。在此之后,程序应该创建一个新数组,使用 memcpy
将旧数组的内容复制到新数组上。最后,将新阵列的内容复制回具有新容量的旧阵列。但是,当我运行程序时,我不断收到运行时错误。此外,根据我调用showStack
函数的位置,我有时会得到 thrash 数字,而不是我推送到堆栈上的实际值。如果有人能指出我做错了什么,我将不胜感激。
#include <iostream>
#include <string>
#include <cstdlib>
#include <cstring>
using namespace std;
class Stack
{
public:
//stack functions
Stack();
void push(int a);
int pop();
int peek() const;
void showStack();
~Stack();
//memory management
void memoryManagement(int a);
//void setCapacity(int );
//void ensureCapacity(int minCapacity);
private:
int top;
int * arr;
int capacity;
int usedCapacity;
};
//////////////////////////////////////////////////////////////////////////////////
int main() {
Stack calc;
calc.push(11);
calc.push(33);
calc.showStack();
calc.push(23);
calc.push(43);
return 0;
}
//////////////////////////////////////////////////////////////////////////////////
Stack::Stack()
{
top = -1;
usedCapacity = 0;
capacity = 1;
arr = new int[capacity];
}
void Stack::push(int a)
{
if (top > capacity)
throw "Stack overflow";
top++;
usedCapacity++;
arr[top] = a;
memoryManagement(usedCapacity);
}
int Stack::pop()
{
if (top <= -1)
throw "Stack underflow";
arr[--top];
}
int Stack::peek() const
{
return top;
}
void Stack::showStack()
{
for (int i = 0; i < capacity; i++)
{
cout << arr[i] << " ";
}
cout << endl;
}
Stack::~Stack()
{
delete[] arr;
}
void Stack::memoryManagement(int a)
{
if (a >= capacity)
{
int newCapacity;
newCapacity = (a * 3) / 2 + 1;
int * arr2 = new int[newCapacity];
memcpy(arr2, arr, sizeof(int) * usedCapacity);
delete[] arr;
arr = arr2;
delete[] arr2;
}
}
为什么要
从memoryManagement
中删除arr2
?你不应该,因为这显然是你的新类属性(你arr = arr2
):
但这还不够(然后您的程序将开始在push
抛出异常......因为您也忘记修改capacity
属性。以下是您的工作memoryManagement
函数:
void Stack::memoryManagement(int a)
{
if (a >= capacity)
{
int newCapacity;
newCapacity = (a * 3) / 2 + 1;
int * arr2 = new int[newCapacity];
memcpy(arr2, arr, sizeof(int) * usedCapacity);
delete[] arr;
arr = arr2;
capacity = newCapacity; // Don't forget that!
//delete[] arr2; // Don't do that!
}
}
相关文章:
- std::向量与传递值的动态数组
- 在c++中用vector填充一个简单的动态数组
- 输出没有重复元素的动态数组(收缩数组)C++
- 正在插入动态数组
- 如何在动态数组上使用搜索函数
- C++ 动态数组每次添加时将大小增加 1 - 错误
- 静态数组的自由动态数组
- 在 c++ 中对类中的 c 字符串动态数组进行排序的最佳方法是什么?
- 使用 thread 类在 C++ 中构造线程的动态数组时出错
- 如何为 c++ 的不同变量类型的结构元素创建动态数组?
- C++ 使用存储在动态数组中的文本文件中的数据查找模式
- 当我使用自定义类型创建动态数组时,即使使用字符串,它似乎也不起作用
- 为什么 c++ 动态数组的大小没有改变?
- 具有自定义构造函数 (C++) 的类型的动态数组分配
- 指针的 C++ 动态数组 - 何时需要使用它?
- 删除动态数组时未定义标识符
- 哈希映射使用 nullptr c++ 初始化节点的动态数组
- 如何将字符串和整数读取到两个单独的动态数组中的程序编写?
- 动态数组的 C++ 重载加运算符
- 基于数组的列表 - 动态数组创建时出错