2016-02-24 107 views
-1

我必须创建一个程序,该程序使用'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; 
      } 
    } 
+1

不要自己使用'new',让'std :: vector'正确地代替它! –

+0

无法为此作业使用矢量。教授希望我们使用常规阵列。 – Sam

+2

[踢你的老师,首先学习C++。](http://dev-jungle.blogspot.de/2015/02/i-have-dream-im-dreaming-of-so-called-c.html) –

回答

1
    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; 

复制后,您将删除旧的数组。然后你也删除刚才分配的新数组。这味道像另一个bug,但它仍不能解释崩溃。现在

   if (!cin.eof()) { 
        array1[count++] = arrayInput; 
       } 

,您可以在这里回答你自己的问题:发生什么事,当你继续写这是指向你释放,近期内存的指针?

这是所示代码中的多个错误。他们都必须修复。在这一点上,我没有看得更远。此代码可能还存在其他问题。 A rubber duck应该能够帮助您在程序中找到任何剩余的错误。

+0

'if(tempArray!= NULL)' - 这对于兼容的编译器不会发生。 – PaulMcKenzie

相关问题