这是我的代码Dyanamic数组类,程序运行良好,但有错误
#ifndef INTLIST_H_INCLUDED
#define INTLIST_H_INCLUDED
#include <iostream>
using namespace std;
class intList
{
int upper_bound;
int arr[0];
public:
intList(){ arr[0] = 0; upper_bound = 0; }
void append(int x);
void sort();
friend ostream & operator << (ostream &, intList&);
inline int len(){ return upper_bound; }
inline int &operator [](int x){ return arr[x]; }
private:
void increment(int *a, int &l);
void swap(int &a, int &b);
};
void intList::swap(int &a, int &b)
{
int temp = a;
a = b;
b = temp;
}
void intList::increment(int *a, int &b)
{
b++;
a[b] = 0;
}
void intList::append(int num)
{
arr[upper_bound] = num;
increment(arr, upper_bound);
}
void intList::sort()
{
for(int i = 0; i < upper_bound; i++)
{
int minLoc = i;
for(int j = i+1; j<upper_bound; j++)
{
if(arr[j] < arr[minLoc])
minLoc = j;
}
if(minLoc != i)
swap(arr[i], arr[minLoc]);
}
}
ostream& operator << (ostream & dout, intList &a)
{
dout << "[ ";
for(int i = 0; i<a.upper_bound-1; i++)
dout << a.arr[i] << ", ";
dout << a.arr[a.upper_bound-1] << " ]";
return dout;
}
#endif // INTLIST_H_INCLUDED
代码没有它的工作完全没有问题。但最后程序崩溃。给出一些错误,如 进程返回-1073741819(0xC0000005)执行时间:几秒钟。
只是没有得到我错在哪里。
我想我得到它。可能它就像阵列在内存位置被赋予连续的空间。在这里,我没有说明需要多少空间。有时间,连接的内存位置可能不是空的,并且程序显示错误。 – tehTerminator
@tehTerminator对,你正在阅读和写作超出数组的范围,到你不应该的地方。 – juanchopanza
@tehTerminator顺便说一句你是否试图将动态大小的数组作为练习?如果是这样,那么在引擎盖下使用'std :: vector'并不是一个真正的解决方案。 – juanchopanza