【问题标题】:C++ Heap memory in array assignment only messing up for the first array and not the second数组分配中的 C++ 堆内存只会弄乱第一个数组而不是第二个数组
【发布时间】:2021-11-03 03:45:26
【问题描述】:

我有一个任务是在名为 insert 和 print 的数组类中创建两个函数。插入应该将元素添加到数组的末尾,当我运行代码时,我得到的输出对于第二个数组来说看起来不错,但第一个数组给出了奇怪的输出。我真的不知道从这里去哪里,任何指针都有帮助

#include <iostream>
using namespace std;
class Array //The array class
{
private:
     //Data members capacity, size, and arr (a pointer that points to the first element of the array in the heap).
     int capacity{};
     int size{};
     int* arr{};
public:
     Array(int capacity);//parameter
     Array();//default
     ~Array();//destructor
     void insert(int num);
     void print() const ;

};
void Array::insert(int num) 
{
     {
          if (size == 0)
          {
               arr[0] = num;
               size++;
               return;
          }
          int index = 0;
          while (num > arr[index] && index < size)
          {
               index++;
          }
          arr[index] = num;
          size++;
     }
}

void Array::print() const
{`enter code here`

     for (int i = 0; i < size; i++)
     {
          cout << *(arr+i)<<" ";
     }

     
     delete[]arr;
}


Array::Array()
{
     return;
}

//Destructor to clean up 
Array::~Array()
{
     return;
}

//Parameter constructor
Array::Array(int cap)
     :capacity(cap)
{
     arr = new int[capacity];
     size = 0;

}

int main()
{

          // Creation of an array with a capacity of 10
          Array array1(10);
          array1.insert(5);
          array1.insert(3);
          array1.insert(2);
          cout << "Array 1: " << endl;
          array1.print();
          cout << endl; 
          // Creation of another array    
          Array array2(20);
          for (int i = 0; i < 20; i++)
          {
               array2.insert(i + 10);
          }
          cout << "Array 2: " << endl;
          array2.print();
          cout << endl;
          return 0;

}

【问题讨论】:

  • 如果你的数组有size元素,它的结尾索引是多少?
  • 很抱歉,显示的代码中有很多错误,很难知道从哪里开始。请注意,在 Array::Array() 中,您不会创建数组。在insert 中,当大小达到容量时,您永远不会增加阵列。析构函数为空,而它应该删除数组。您的打印功能会删除数组。所有这些都是严重错误。首先确保您了解new[]delete[] 的作用,以及构造函数和析构函数的用途。
  • 谢谢我通过将删除移动到析构函数、初始化分配的数组以及将删除数组移出打印函数来解决一些错误。我现在得到 2 0 0 的 Array1 输出,这是朝着正确方向迈出的一步,因为我不再获得垃圾值
  • 感谢您的帮助,我能够正确打印出数字

标签: c++ arrays c++11 heap-memory


【解决方案1】:

你没有初始化分配的数组

arr = new int[capacity];

所以它的内容是垃圾。

然后在您的insert() 中尝试按升序插入元素,但不会向上移动现有元素;你只需覆盖它们。

你的print 打印的垃圾。

第二个测试用例有效,因为您的元素已经排序,因此无需移动。

【讨论】:

  • 我编辑了上述行并将其替换为 arr = {new int[capacity] {}};第一个数组现在打印出 2 0 0,一个新的错误是进度 :) 谢谢你发现
  • 感谢您的帮助,我能够正确打印出数字
  • @AngelArmendariz 欢迎您。如果你觉得我已经回答了你的问题,你可以接受:stackoverflow.com/help/accepted-answer
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-27
  • 2017-09-08
  • 1970-01-01
  • 2022-07-21
  • 1970-01-01
相关资源
最近更新 更多