Hi everyone:
I would appreciate some help with understanding how to free memory/use destructors.
I have created a 2D dynamic array template class. I'm using Xcode and Xcode keeps crashing, with the message, "out of memory." Before I implemented this array class, I was using "new" directly within main() to create my dynamic matrices and had no problems.
Two possible problems have occurred to me, and I would be very grateful for any further guidance.
1) I may not understand correctly how to use destructors (more below).
2) I am overloading () to use (i,j) for indexing within my arrays. But my destructor uses indexing, because I couldn't figure out how to use (i,j) indexing within the destructor--the destructor works like this:
template <typename T>
Array2d<T>::~Array2d()
{
for(int i = 0; i < rows; i++)
{
delete[ ] array[i];
}
delete[ ] array;
}
Maybe [] is not compatible with (). If it isn't, I don't know how to use () in the destructor.
When I say that I may not know correctly how to use destructors, I mean that I'm not sure HOW to call the destructor in main().
1) If arrayInstance is the name of my class instance I create in main, I have tried:
delete arrayInstance;
This produces the error: Type 'class Array2D<double>' argument given to delete expected pointer
2) I have also tried implementing the code above for my destructor within a delete function in the Array2D class:
arrayInstance.deleteArray2D();
This causes Xcode to crash with the "out of memory" message.
3) I have tried in main():
for (int i = 0; i < rows; i++)
{
delete[ ] arrayInstance[ i ];
}
delete[ ] arrayInstance;
This also causes Xcode to crash with the "out of memory" message.
Can anyone suggest what the problem might be? By the way, here is my constructor (cpp file), in case that is useful:
template <typename T>
Array2D<T>::Array2D(int rowsPub, int colsPub)
: rows(rowsPub), cols(colsPub)
{
arrayInstance = new T* [ rows ];
for (int i = 0; i < rows; i++)
arrayInstance = new T[ cols ];
}
And I declare my data members of the class in the header:
int rows, cols;
T** array;