I cannot figure out why this keeps crashing on me. The code makes it almost to the end. Specifically it makes it to the print(copyArray); line. I have no idea where I went wrong, but it keeps popping up the same error.
I have tried calling the destructors, but apparently I am not doing it right.
elementArray.~ManagedArray();
EDIT:
I read that entire thread you posted and still cannot find the answer. I did however figure out if I comment out the print functions it does not occur. But once I print it crashes at the end of the function.
#include <iostream>
using namespace std;
class ManagedArray
{
private:
int numberOfElements;
float *elements;
public:
ManagedArray(): numberOfElements(0), elements(NULL){}
int size();
float get(int index);
void add(float value);
ManagedArray(ManagedArray & ma);
~ManagedArray() {delete [] elements;}
};
ManagedArray::ManagedArray(ManagedArray & ma):numberOfElements(ma.numberOfElements)
{
elements = ma.elements;
}
int ManagedArray::size()
{
return numberOfElements;
}
float ManagedArray::get(int index)
{
return elements[index];
}
void ManagedArray::add(float value)
{
float * BiggerArray = new float[numberOfElements+1];
if(elements != NULL)
{
// copy the old elements into the biggerArray
for(int i = 0; i < numberOfElements; i++)
{
BiggerArray[i] = elements[i];
}
// the old array is not needed anymore, we have a better copy
this->~ManagedArray();
}
elements = BiggerArray;
numberOfElements = numberOfElements+1;
// put the new number into the last element of the array
elements[numberOfElements-1] = value;
}
void print(ManagedArray ma)
{
// print the stored numbers
cout << "Entered numbers: " << endl;
cout << "{";
for(int i = 0; i < ma.size(); ++i)
{
if(i > 0)
{
cout << ", ";
}
cout << ma.get(i);
}
cout << "}" << endl;
float sum = 0;
for(int i = 0; i < ma.size(); ++i)
{
sum += ma.get(i);
}
cout << "total: " << sum << endl;
cout << "average: " << (sum / ma.size()) << endl;
}
int main()
{
float userInput;
ManagedArray elementArray;
bool addingNumbersToTheList;
cout << "Keep entering numbers. Enter a non-number to stop." << endl;
do
{
cin >> userInput;
addingNumbersToTheList = !std::cin.fail();
if(addingNumbersToTheList) {
elementArray.add(userInput);
}
}
while(addingNumbersToTheList);
// fix cin after intentionally breaking it above.
if(std::cin.fail())
{
std::cin.clear();
while(std::cin.get() != '\n');
}
bool hasNumbers = elementArray.size() > 0;
if(hasNumbers) {
ManagedArray copyArray(elementArray);
cout << "printing elementArray:\n";
print(elementArray);
cout << "\nprinting copyArray:\n";
print(copyArray);
}
else
{
cout << "no numbers entered." << endl;
}
cin.get();
cin.get();
return 0;
}