0

I am writing a code to multiply matrices of any dimensions. I noticed it works fine for square matrices as well as when the outer dimensions are greater than inner. However, I can't get it to work for cases where outer dimensions are smaller then inner, such as multiplying a 2X3 matrix with a 3X2 matrix. For these cases, it straight away terminates without printing anything. In the working cases, the correct resultant matrix is being printed.

Below is my code after taking inputs and calculating the resultant matrix. arr1 is a m1Xn1 matrix and arr2 is a m2Xn2 matrix.

int *res = (int*)calloc(m1*n2, sizeof(int));
for(int i = 0; i < m1; i++){
    for(int j = 0; j < n2; j++){
        *(res + i*m1 + j) = 0;
        for(int k = 0; k < n1; k++){
            *(res + i*m1 + j) += *(arr1 + i*m1 + k) * *(arr2 + k*n2 + j);
        }
        //printf("%d,%d = %d\n", i, j, *(res + i*m1 + j));
    }
}

Can someone please explain what's going wrong?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
  • 2
    Unrelated to your problem, but note that for *any* pointer or array `p` and index `i`, the expression `*(p + i)` is *exactly* equal to `p[i]`. The latter (`p[i]`) is typically easier to read and understand, as well as less to write. – Some programmer dude Jun 01 '20 at 05:26
  • Also unrelated to your problem, but the initial `c` in `calloc` stands for *clear*. The [`calloc`](https://en.cppreference.com/w/c/memory/malloc) function *clears* the memory, it sets all bytes to zero. That means your assignment to zero isn't needed. Also please [don't cast the result of `malloc` (or `calloc`)](https://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc). – Some programmer dude Jun 01 '20 at 05:29
  • 2
    If your inferior dimension is `n2`, then you column offset calculation is wrong. it shouldn't be `res + i*m1 + j`, for example, it should be `res + i*n2 + j`. I believe this problem happens in a couple of places in your code. `i` is the "row", which is effectively a multiplier of columns. – WhozCraig Jun 01 '20 at 05:32
  • To make life easy for yourself: define an accessor function `int elem(int* mat, int i, int j)` that returns the (i, j)th element of `mat` – Hong Ooi Jun 01 '20 at 05:32
  • Might help if you included an example arr1 arr2 etc. that demonstrate the problem. – gmatht Jun 01 '20 at 05:35

0 Answers0