gpt4 book ai didi

C++ 调整动态数组的大小最多可以处理一定数量的元素,但有时会因错误 (0XC0000005) 而崩溃

转载 作者:行者123 更新时间:2023-11-27 23:46:34 24 4
gpt4 key购买 nike

抱歉,如果之前已经回答过这个问题。我搜索了调整动态数组的大小,所有的建议似乎都是使用 STL Vector,但我正在做一个任务,重点是制作我自己的最小 vector 模板类。

我的 vector 类需要存储从输入文件中读取而创建的动态结构数组。它必须做的一件事是在满时调整大小。它工作到一定程度 - 处理 52207 行中的 5121 行,然后崩溃并出现错误“进程返回 -1073741819 (0XC0000005)”。

我环顾四周,发现这是一个内存分配错误。我是编程和 C++ 的新手,我对我的程序中的原因感到困惑。我假设它在我调整数组代码的大小中。任何帮助将不胜感激!

我的 vector 模板代码:

#ifndef VECTOR_H
#define VECTOR_H

#include <iostream>

using namespace std;

template <class T>
class Vector {
public:
/// Constructor
Vector();
/// Copy constructor
Vector(const Vector<T>& otherVector);
/// Destructor
virtual ~Vector();
/// assignment operator
const Vector<T>& operator= (const Vector<T>&);
/// methods
void addElement(const T& newElement);
T getElement(int index) const;
int getLength() const;

protected:
int arraySize;
int length;
T *p;

};

template <class T>
Vector<T>::Vector()
{
arraySize = 10;
length = 0;

p = new T[arraySize];
}

template <class T>
Vector<T>::Vector(const Vector& otherObject)
{
arraySize = otherObject.arraySize;
length = otherObject.length;

p = new T[arraySize];

for(int i = 0; i < length; i++)
p[i] = otherObject.p[i];
}

template <class T>
Vector<T>::~Vector()
{
delete [] p;
}

template <class T>
const Vector<T>& Vector<T>::operator= (const Vector<T>& newVector)
{
if(this != &newVector)
{
delete [] p;
arraySize = newVector.arraySize;
length = newVector.length;

p = new T[arraySize];

for(int i = 0; i < length; i++)
p[i] = newVector.p[i];
}
return *this;
}

template <class T>
void Vector<T>::addElement(const T& newElement)
{
if(length == arraySize)
{
// create a new resized array
T *temp;
temp = new T[arraySize*2];

// copy elements of p into temp
for(int i = 0; i < length; i++)
{
temp[i] = p[i];
}

// delete p and create new p and set equal to temp
delete [] p;
arraySize *= 2; // set array size to double
p = new T[arraySize];
p = temp;

// delete temp array
delete [] temp;

// add new element and incerement length;
p[length] = newElement;
length++;

}
else
{
p[length] = newElement;
length++;
}
}

template <class T>
T Vector<T>::getElement(int index) const
{
return p[index];
}

template <class T>
int Vector<T>::getLength() const
{
return length;
}

#endif

最佳答案

您的调整大小逻辑有误。在您到达这里之前,一切都很好。

p = new T[arraySize];
p = temp;

delete [] temp;

您分配一个新数组,然后立即让 p 指向 temp 指向的数据。然后删除 temp 指向的数据,它与 p 相同,这意味着 p 指向释放的内存;它是一个悬空引用,未定义通过 p

访问任何内容

不过修复起来很简单:去掉分配和删除,只需要有赋值的那一行:

  // p = new T[arraySize];
p = temp;
// delete [] temp;

p 不需要新空间,temp 已经有了。只需将它交给 p。然后你不删除 temp,因为 p 正在管理它。

关于C++ 调整动态数组的大小最多可以处理一定数量的元素,但有时会因错误 (0XC0000005) 而崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50085136/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com