dimanche 5 septembre 2021

C++ Heap memory in array assignment only messing up for the first array and not the second

I have an assignment to create two functions in an array class named insert and print. Insert should add elements to the end of the array and when I run the code, I get output that looks fine for the second array but the first array gives strange output. I don't really know where to go from here and any pointers help Image of my output

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

}

Aucun commentaire:

Enregistrer un commentaire