I have written some code to dynamically allocate memory for a 2D matrix. I am using overload operator to perform functions on the matrix naturally. I am having memory issues (Unhandled exception at 0x... Access violation reading ...). Here is my class, header, and main code. The code builds fine with no errors or warnings but I get severe problems when I run it.
// HEADER FILE
#include <iostream>
#include <iomanip>
#include <stdlib.h>
using namespace std;
typedef int p2dArrayData;
class p2dArray
{
public:
p2dArray();
p2dArray (int rows, int cols);
p2dArray operator+(const p2dArray&);
p2dArray& operator=(const p2dArray&);
~p2dArray();
private:
int HEIGHT;
int WIDTH;
p2dArrayData **contents;
};
// Matrix Class
#include <iostream>
#include <iomanip>
#include <stdlib.h>
#include "p2dArray.h"
using namespace std;
p2dArray::p2dArray()
{
}
p2dArray::p2dArray(int ROWS_Given, int COLS_Given)
{
HEIGHT = ROWS_Given;
WIDTH = COLS_Given;
contents = new p2dArrayData* [ROWS_Given];
for (int i = 0; i < ROWS_Given; i++) {
contents[i] = new p2dArrayData [COLS_Given];
}
for(int i = 0; i < ROWS_Given; i++) {
for(int j = 0; j < COLS_Given; j++) {
contents[i][j] = (p2dArrayData) i * j;
}
}
}
// Deep Copy Constructor
p2dArray& p2dArray::operator=(const p2dArray& operand)
{
if(this != &operand) {
for(int i = 0; i < operand.HEIGHT; i++) {
for(int j = 0; j < operand.WIDTH; j++) {
contents[i][j] = operand.contents[i][j];
}
}
}
return *this;
}
// Overloaded + Operator
p2dArray p2dArray::operator+(const p2dArray& operand)
{
p2dArray temp2d(HEIGHT, WIDTH);
if(HEIGHT != operand.HEIGHT && WIDTH != operand.WIDTH) throw(1);
for(int i = 0; i < HEIGHT; i++) {
for(int j = 0; j < WIDTH; j++) {
temp2d.contents[i][j] = contents[i][j] + operand.contents[i][j];
}
}
return temp2d;
}
// Destructor
p2dArray::~p2dArray()
{
for (int i = 0; i < HEIGHT; i++)
delete[] contents[i];
delete [] contents;
}
// MAIN FILE
#include <iostream>
#include <iomanip>
#include <stdlib.h>
#include "p2dArray.h"
using namespace std;
int main()
{
p2dArray first(2, 3);
p2dArray second(2, 3);
first = second + first;
return 0;
}
I believe the problem may be in my copy constructor. However, if I remove the destructor, I get no errors so I might not be doing that right either. I am at a loss.