So I'm writing some code that does some matrix operations (namely multiplications) I've created a separate class for manipulating the matrices. The matrix itself has memory for it allocated within the class. Here's a sample of what I'm talking about...
Expand|Select|Wrap|Line Numbers
- Matrix* Matrix::multiply(const Matrix &b) {
- assert(c == b.r);
- Matrix *result = new Matrix(r, b.c);
- for (int i = 0; i < b.c; i++)
- for (int j = 0; j < r; j++)
- for (int k = 0; k < c; k++)
- result->matrix[i][j] += matrix[i][k] * b.matrix[k][j];
- return result;
- }
Expand|Select|Wrap|Line Numbers
- Matrix::Matrix(int _r, int _c) {
- r = _r;
- c = _c;
- matrix = (double**)malloc(r*sizeof(double*));
- for (int i = 0; i < r; i++) {
- matrix[i] = (double*)malloc(c*sizeof(double));
- memset(matrix[i], 0x00, c*sizeof(double));
- }
- }
Expand|Select|Wrap|Line Numbers
- Matrix::~Matrix() {
- for (int i = 0; i < r; i++)
- free(matrix[i]);
- free(matrix);
- }
Expand|Select|Wrap|Line Numbers
- Matrix a(3,1);
- Matrix b(3,3);
- Matrix *r = NULL;
- //values fo the matrix are initialized here...
- r = b.multiply(a);
- r->print();
- delete r; //source of error...
I'm flustered, thanks in advance to anyone that has suggestions!