我必须创建一个程序,该程序使用'new'运算符在程序堆中创建一个动态数组。该程序为每个输入数据(cin)一次创建并填充其动态数组one(int)元素。动态数组:需要帮助将一个数组复制到另一个
关键部件。
1.)程序必须使用“cin >>”来输入数据,以一次接受整数,直到在键盘上按下EOF(窗口的cntrl-z)。要使用!cin.eof()& & cin.good()来测试用户输入是否被按下,以及数据是否有效。 (对cin.good()部分有些困惑)。
3.)该程序将创建一系列更长和更长的数组,以包含所有先前的元素和当前传入的元素。此外,程序将在完成当前版本后删除先前版本的阵列。
4.)程序还测试每次使用新操作符后堆内存是否已耗尽。 (需要帮助)
我不断收到错误信息“HEAP CORRUPTION DETECTOR After normal black(#146)”(visual studio)。有什么问题?
在此先感谢!
下面的代码:
#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <cassert>
using namespace std;
// main
int main() {
int size = 2;
int * array1 = new int[size];
int arrayInput;
int count = 0;
do {
if (array1 != NULL) {
cout << "Enter an integer (EOF to stop): " << endl;
cin >> arrayInput;
if (size < count) {
int * tempArray;
tempArray = new int[size * 2];
if (tempArray != NULL)
{
for (int i = 0; i < size; i++) {
array1[i] = tempArray[i];
}
delete[] array1;
array1 = tempArray;
size *= 2;
delete [] tempArray;
}
else
cout << "Insufficient Heap resource." << endl; // If we get here the Heap is out of space
}
if (!cin.eof()) {
array1[count++] = arrayInput;
}
}
else
cout << "Insufficient Heap resource." << endl; // If we get here the Heap is out of space
} while (!cin.eof());
for (int i = 0; i < count; i++) {
cout << array1[i] << endl;
}
}
不要自己使用'new',让'std :: vector'正确地代替它! –
无法为此作业使用矢量。教授希望我们使用常规阵列。 – Sam
[踢你的老师,首先学习C++。](http://dev-jungle.blogspot.de/2015/02/i-have-dream-im-dreaming-of-so-called-c.html) –