• (2 Pages)
• 1
• 2

## 16 Replies - 9902 Views - Last Post: 30 September 2012 - 02:40 PMRate Topic: //<![CDATA[ rating = new ipb.rating( 'topic_rate_', { url: 'https://www.dreamincode.net/forums/index.php?app=forums&module=ajax&section=topics&do=rateTopic&t=293399&amp;s=f7506603bfcfab2a4d43adba52c451ad&md5check=' + ipb.vars['secure_hash'], cur_rating: 0, rated: 0, allow_rate: 0, multi_rate: 1, show_rate_text: true } ); //]]>

### #1 Aramyth

Reputation: 5
• Posts: 51
• Joined: 14-January 10

Posted 27 September 2012 - 07:51 AM

Hi all,

I'm working on this Matrix class with operator overloading. For the sake of learning it and brushing up on my C++.

I'm trying overload opertator+ and it seems to be working in a sense that syntax is correct, however my program crashes when I try to multiply two matrices together.

I've added the entire code below. Could someone just help me debug this? I can't seem to figure it out.

```#ifndef MATRIX_H
#define MATRIX_H

#include <stdio.h>
#include <math.h>
#include "Vector.h"

class Matrix {

public:

~Matrix(); //Deconstructor

unsigned int _rows, _cols;
Matrix (unsigned int rows, unsigned int cols);
float** pointerMatrix; //pointer to a pointer matrix

void assignmentOperator(const Matrix& a);
float & operator()(const int r, const int c); //overload operator for () for cell assignment

//Basic Functions
void print(); 	//Print Matrix
Matrix multiplyVector (Vector vector1); 	//Matrix multiply by vector
Matrix& operator= (const Matrix& a);
friend Matrix operator+ (const Matrix& firstMatrix,  const Matrix& secondMatrix); //Matris Addition

};

#endif
```

```#include "Matrix.h"

Matrix::Matrix(unsigned int rows, unsigned int cols) {
pointerMatrix = NULL;
//check to make sure that rows/cols are greater than zero
//however pointless with unsigned ints
if (rows > 0 && cols > 0) {
_rows = rows;
_cols = cols;
}

pointerMatrix = new float*[rows];

for (int r = 0; r < rows; r++) {

pointerMatrix[r] = new float[rows];

for (int c = 0; c < cols; c++) {
//initially fill the matrix with all zero values
pointerMatrix[r][c] = 0.0f;
}//end for cols
}//end for rows

}//end constructor

//assignment operator
void Matrix::assignmentOperator(const Matrix& a) {
_rows = a._rows;
_cols = a._cols;
pointerMatrix = new float*[a._rows];
for (int r = 0; r < a._rows; r++) {
pointerMatrix[r] = new float[a._cols];

// copy the values from the matrix a
for (int c = 0; c < a._cols; c++) {
pointerMatrix[r][c] = a.pointerMatrix[r][c];
}
}
}

float& Matrix::operator()(const int r, const int c) {
if (pointerMatrix != NULL && r > 0 && r <= _rows && c > 0 && c <= _cols) {
return pointerMatrix[r-1][c-1];
} else {
throw printf("%c", "Out of Bounds Exception");
}
}

Matrix& Matrix::operator=(const Matrix& a) {
_rows = a._rows;
_cols = a._cols;
pointerMatrix = new float*[a._rows];

for (int r = 0; r < a._rows; r++) {
pointerMatrix[r] = new float[a._cols];

// copy the values from the matrix a
for (int c = 0; c < a._cols; c++) {
pointerMatrix[r][c] = a.pointerMatrix[r][c];
}
}

return *this;
}

Matrix operator+ (const Matrix& firstMatrix, const Matrix& secondMatrix) {
// check if the dimensions matc
if (firstMatrix._rows == secondMatrix._rows && secondMatrix._cols == secondMatrix._cols) {

Matrix result(firstMatrix._rows, firstMatrix._cols);

for (int r = 0; r < firstMatrix._rows; r++)  {
for (int c = 0; c < firstMatrix._cols; c++) {
result.pointerMatrix[r][c] = firstMatrix.pointerMatrix[r][c] + secondMatrix.pointerMatrix[r][c];
}
}

return result;
}

}

void Matrix::print() {
if (pointerMatrix != NULL) {
printf("\n [");
for (int r = 0; r < _rows; r++) {
if (r > 0)
{
printf(" ");
}
for (int c = 0; c < _cols-1; c++) {
printf("%.2f, ", pointerMatrix[r][c]);
}
if (r < _rows-1) {
printf("%.2f;\n", pointerMatrix[r][_cols-1]);
} else {
printf("%.2f]\n", pointerMatrix[r][_cols-1]);
}
}
} else {
// matrix is empty
printf("[ ]\n");
}
}//end print function

//Deconstructor
Matrix::~Matrix() {
// clean up allocated memory
for (int r = 0; r < _rows; r++) {
delete pointerMatrix[r];
}
delete pointerMatrix;
pointerMatrix = NULL;
}

```

```int rows = 3;
int cols = 3;

int main () {

Matrix one = Matrix(rows, cols);
Matrix two = Matrix(rows, cols);
one(1,1) = 6.0f;  //created my own index, starts at 1,1
one(1,2) = 3.0f; //the rest of the elements would have zeros filled in on them

Matrix result = one + two;

result.print();

system("PAUSE");

return 0;
}

```

Is This A Good Question/Topic? 0

## Replies To: Matrix Class with Operator overloading - need help debugging

### #2 Skydiver

• Code herder

Reputation: 6217
• Posts: 21,462
• Joined: 05-May 12

Posted 27 September 2012 - 08:39 AM

When you run your code in the debugger. Where is it indicating a crash?

### #3 Aramyth

Reputation: 5
• Posts: 51
• Joined: 14-January 10

Posted 27 September 2012 - 09:13 AM

It will just crash and prompt me to use the "just in time debugger". I've never seen this before.

When I hit break, it'll bring me to a line in my print method.

``` for (int c = 0; c < _cols-1; c++) {
printf("%.2f, ", pointerMatrix[r][c]);
}
```

But print works when not adding any matrices. So it has something to do with the matrix addition I believe.

### #4 Skydiver

• Code herder

Reputation: 6217
• Posts: 21,462
• Joined: 05-May 12

Posted 27 September 2012 - 10:10 AM

With the debugger there, if you look at the local variables, does the this pointer look correct? Do the class member variables have correct values for _cols and _rows? Is the pointerMatrix pointing to an array of pointers, and do the array of pointers point to what looks like valid floating point numbers?

### #5 Aramyth

Reputation: 5
• Posts: 51
• Joined: 14-January 10

Posted 27 September 2012 - 05:07 PM

My debugging skills have always been lacking. so I'm really sure how to tell if it looks correct or not...

### #6 #define

• Duke of Err

Reputation: 1853
• Posts: 6,671
• Joined: 19-February 09

Posted 27 September 2012 - 05:25 PM

Hi, I think you need to define a copy constructor. The default copy constructor will not allocate memory and not copy the data properly.

You could create some subroutines to allocate and deallocate memory, and copy data.

### #7 Aramyth

Reputation: 5
• Posts: 51
• Joined: 14-January 10

Posted 28 September 2012 - 09:55 AM

I'll try that later tonight. Thanks.

### #8 Aramyth

Reputation: 5
• Posts: 51
• Joined: 14-January 10

Posted 30 September 2012 - 12:05 PM

I haven't been able to fix this, I was wondering if anyone could help me with some example code.

I've found it's throwing an error CXX0030: Expression cannot be evaluated. But I'm not sure how to go about fixing this one.

This post has been edited by Aramyth: 30 September 2012 - 12:09 PM

### #9 jimblumberg

Reputation: 5487
• Posts: 17,064
• Joined: 25-December 09

Posted 30 September 2012 - 12:09 PM

Post your latest code along with the complete error messages, exactly as they appear in your development environment. Then ask specific questions based on the information you provided.

Jim

### #10 Aramyth

Reputation: 5
• Posts: 51
• Joined: 14-January 10

Posted 30 September 2012 - 12:53 PM

I reverted all changes because they made no progress, I am still working with the code in the original post.

The error is showing in the debugger as "error CXX0030: Expression cannot be evaluated" and is appearing on line 98 of my Matrix.cpp when trying to print the result of two matrices added together.

Sorry if it wasn't clear the first time.

### #11 Skydiver

• Code herder

Reputation: 6217
• Posts: 21,462
• Joined: 05-May 12

Posted 30 September 2012 - 01:00 PM

I think that #define's comments are on the right track. You are ending up with an invalid Matrix being returned by your function. This is why I was asking if you had a valid this pointer, and if the contents of your class looked correct.

### #12 jimblumberg

Reputation: 5487
• Posts: 17,064
• Joined: 25-December 09

Posted 30 September 2012 - 01:11 PM

Did you Google that error message? That message seems to indicate you are trying to access memory you don't own. What are the values of your array indexes? Are they valid values.

You need to show us what you have tried so we don't go over the same ground.

Sorry if I wasn't clear the first time.

Also since this is C++ why are you using C stdio functions instead of C++ streams.

Since we can't compile your code (missing Vector) you will need to show exactly what you have tried and the outcome of these trials.

Jim

This post has been edited by jimblumberg: 30 September 2012 - 01:13 PM

### #13 Aramyth

Reputation: 5
• Posts: 51
• Joined: 14-January 10

Posted 30 September 2012 - 01:24 PM

Remove the #include "Vector.h" and
```Matrix multiplyVector (Vector vector1);
```
in Matrix.h and you should be able to compile this code.

The defines:
```#ifndef MATRIX_H
#define MATRIX_H
```

Are what I have always used and have been told to use. Are they incorrect?

I'm confused as to what's going on because it's throwing errors when trying to print the result of the addition of two matrices. If you try to print matrices that are just created, then it's fine.

I've tried approaching the constructor from a different angle, but it didn't help

```Matrix::Matrix() {
pointerMatrix = NULL;
_rows = 0;
_cols = 0;
}

```

This post has been edited by Aramyth: 30 September 2012 - 01:27 PM

### #14 #define

• Duke of Err

Reputation: 1853
• Posts: 6,671
• Joined: 19-February 09

Posted 30 September 2012 - 01:28 PM

A copy constructor is a constructor that has a parameter of the class type. It makes a copy of a class object from another object of the same class.

You can add this to see if the copy constructor is called.

```Matrix::Matrix (const Matrix &rhs)
{
cout << endl;
cout << "Copy constructor called" << endl;
}

```

This post has been edited by #define: 30 September 2012 - 01:29 PM

### #15 jimblumberg

Reputation: 5487
• Posts: 17,064
• Joined: 25-December 09

Posted 30 September 2012 - 01:39 PM

There are a couple of problems with your code, they may not be the actual cause of your problems but they probably contribute to the problems:
```float& Matrix::operator()(const int r, const int c) {
if (pointerMatrix != NULL && r > 0 && r <= _rows && c > 0 && c <= _cols) {
return pointerMatrix[r-1][c-1];
} else {
throw printf("%c", "Out of Bounds Exception");
}
}
```

Look closely at that printf() this is using the wrong format specifier "%c" is for a single character not a C-string. This is one of the reasons I asked why you are using C-stdio functions rather than C++ streams.

Next in this snippet:
```Matrix operator+ (const Matrix& firstMatrix, const Matrix& secondMatrix) {
// check if the dimensions matc
if (firstMatrix._rows == secondMatrix._rows && secondMatrix._cols == secondMatrix._cols) {

Matrix result(firstMatrix._rows, firstMatrix._cols);

for (int r = 0; r < firstMatrix._rows; r++)  {
for (int c = 0; c < firstMatrix._cols; c++) {
result.pointerMatrix[r][c] = firstMatrix.pointerMatrix[r][c] + secondMatrix.pointerMatrix[r][c];
}
}

return result;
}

}

```

If your if statement doesn't evaluate to true you fail to return a value. This is very dangerous you need to return something.

Also since you have pointer members you probably should create a default no parameter constructor, a copy constructor, along with your destructor.

Jim

This post has been edited by jimblumberg: 30 September 2012 - 01:42 PM