简体   繁体   中英

C language - Matrix multiplication bug

I'm trying to write a code that gets a matrix A and its dimensions, a matrix B and its dimensions, and returns a matrix C such that C=AB .

It's safe to assume that the number of columns of A is equal to the number of rows of B and so C=AB is defined

This is my code:

int *matrix_multiplication(int *A,int row_A,int column_A,int *B,int row_B,int column_B)
{
    int row_C,column_C,*C,i,j,k,sum=0;
    row_C=row_A;
    column_C=column_B;
    C=(int*)malloc(row_C*column_C*sizeof(int));
    for(i=0;i<row_C;i++)
    {
        for(j=0;j<column_C;j++)
        {
            for(k=0;k<column_A;k++)
                sum+=(*(A+column_A*i+k))*(*(B+column_B*k+j));//A[i][k]B[k][j]
            *(C+row_C*i+j)=sum;
            sum=0;
        }
    }
    return C;
}

A little explanation: I view a matrix as a single dimensional array, of size columns*rows*sizeof(int) and the given formula A[i][j]=*(A+column_A*i+j) where A is pointer to the first element of the array, and column_A is the amount of columns in "matrix" A .

My problem is that my code does not work for some inputs when row_C != column_C

For example, if A=[28,8,12;14,5,45] and B=[31;27;11] it returns C=[1216;-842150451]

Why does this happen? I can't seem to find the bug.

Try

*(C+column_C*i+j)=sum;

it might be an idea to make a function or macro for accessing matrix elements. That way similar problems in the future can be avoided. Better than that make a matrix class with method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM