i start with:
typedef struct
{
int rows, cols;
int **element;
}Matrix;
and i create two matrices:
void matrixInit (Matrix *m, int r, int c )
{
m->element = malloc(sizeof(int*)*r);
for (int j=0;j<3;++j)
{
m->element[j] = malloc(sizeof(int)*c);
}
m->rows=r;
m->cols=c;
}
Matrix m1,m2,m3;
matrixInit(&m1,3,3);
for (k=0; k<m1.cols*m1.rows; k++)
{
m1.element[k]=q;
q++;
}
then i do matrix 2 using copy function created
void matrixCopy (Matrix *m, Matrix *n )
{
int r=n->rows,c=n->cols,k;
for (k=0; k<r*c; k++)
{
m->element[k]=n->element[k];
}
}
matrixInit(&m2, 3, 3);
matrixCopy(&m2, &m1);
and then i create a third to be the result of the addition
matrixInit(&m3, 3, 3);
then i do the addition. this is where my problem lies. I cannot seem to get this to work.
my code for the function is below: (the prototype must stay the same)
Matrix* matrixAdd (Matrix *m, Matrix *n )
{
int q;
for (q=0; q<m->rows*m->cols; q++)
{
m->element[q]=*m->element[q]+*n->element[q];
}
return m;
}
m3=*matrixAdd(&m1, &m2);
m3, and two-matrices (m3 and m1) that are pointing to the same buffer. In summary, that isn't good.for (int j=0; j<3; ++j)loop should befor (int j=0; j<r; ++j)(rinstead of3); (b) the function creates but does not initialize the matrix; the values in the cells is indeterminate. For pity's sake, please use spaces: the loopfor (q=0; q<m->rows*m->cols; q++)is damned hard to read, compared with:for (q = 0; q < m->rows * m->cols; q++).m3 == &m1after the call, returning the matrix as a pointer is a little pointless. Either you need to allocate a result matrix in the function or you don't need to return a pointer to the result. Since you can't change the prototype, you need to allocate the matrix in the addition function.