runnercto
runnercto

Reputation: 11

adding two two-dimensional arrays in C

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);

Upvotes: 0

Views: 136

Answers (1)

doptimusprime
doptimusprime

Reputation: 9395

matrixAdd function should be as follows: * on element will refer to first value only.

Matrix* matrixAdd (Matrix *m, Matrix *n )
{
    int q;
    int r;
    for(r = 0; r<m->rows; ++r)
       for (q=0; q<m->cols; q++)
       {
           m->element[r][q]=m->element[r][q]+n->element[r][q];
       }

    return m;
}

This will be more readable can be understood.

In your case,

   *m->element[q] = *m->element[q]+*n->element[q];

will lead you into problem as you have allocated r pointers to int * (therefore r continuous element) and at each pointer you have allocated c integers.

Therefore, if q is beyond r, behaviour is not defined.

Upvotes: 1

Related Questions