JCole - 10 months ago 54

C++ Question

I've been having problems getting a regular 2d array to be filled with the base class that I have Complex(). I have the array initialized in the constructor of the derived class matrix() and i'm making sure I fill it properly but I keep getting an error no matter what I do. I keep getting access violation writing location which probably means the array is not initialized properly and the data I'm writing is written to the CPU instead. Here is my Matrix.h file

`#pragma`

#ifndef MATRIX_H

#define MATRIX_H

#include "Complex.h"

#include "stdafx.h"

#include <iostream>

using namespace std;

class Matrix : public Complex

{

private:

Complex **a;

double real;

double imag;

double length, width;

public:

Matrix(): real( 0.0 ), imag( 0.0 ) {}

void setMatrix(int b , int c) {

int i, j;

a=new Complex*();

length=b, width=c;

for(int k=0;k<b;k++)

for(int p=0; p<c; p++)

a[k]=new Complex();

for (i = 0; i <= b; i++)

for (j = 0; j<= c; j++)

a[i][j].setImag(rand() % 100);

a[i][j].setReal(rand() % 100);

}

Matrix add( const Matrix & ) const;

void print() const;

void setMatrix(int b, int c) const;

};

#endif

Here's my Matrix.cpp file

`#include <iostream>`

using namespace std;

#include "Matrix.h"

Matrix Matrix::add( const Matrix &c ) const

{

Matrix result;

result.setMatrix(2,2);

int i,j;

for(i=0; i<c.length; i++) {

for(j=0; j<c.width;j++) {

result.a[i][j].setImag(a[i][j].getImag() + c.a[i][j].getImag());

result.a[i][j].setReal(a[i][j].getReal() + c.a[i][j].getReal());

}

}

return result;

}

void Matrix::print() const {

for(int i=0; i<length; i++) {

for(int j=0; j<width; j++) {

cout << "(" << a[i][j].getReal() << "," << a[i][j].getImag() << ")/n";

}

}

}

Any help will be appreciated!

Answer Source

I am not even going to try and fix all the things that are wrong with this code, so you are going to run into more problems, but as far as the memory allocation is concerned

```
a=new Complex*();
```

only allocates a single complex, so only `a[0]`

is valid. This must be replaced with

```
a=new Complex*[length];
```

The same goes for

```
a[k]=new Complex();
```

which must be replaced with

```
a[k]=new Complex[width];
```

so the allocation in `setMatrix`

becomes:

```
void setMatrix(int b , int c)
{
length=b;
width=c;
a=new Complex*[length];
for(int k=0;k<length;k++)
{
a[k]=new Complex[width];
}
}
```

Notes:

- don't use
`using namespace std`

in a header. - prefer not using
`using namespace std`

- You need a destructor if you use raw pointers
- print should not be part of Matrix
- Matrix should prob. not derive from Complex ...