0

[I don't understand why z4][4] = ... (in the imange) I want to code a program that can make matrices multiplication but when I run my code with two 2x2 matrices, my output z[1][1], z[1][2], z[2][1] is the same that I expected (value), only z[2][2] is printed with its address. I have tried with bigger matrices, my bug happened with more entry. Can someone help me.

#include <stdio.h>
int main() {
    const int m,n,k;
    scanf("%d %d %d",&m,&n,&k);  // size of 3 matrices
    int a[m][n];
    int b[n][k];
    int z[m][k];
    int i,j,e,r,v,x,c;
    for (i=1;i<=m;i++){                            // declare matrix a
        for (j=1;j<=n;j++){
            scanf("%d",&a[i][j]);   
        }
        
    }
    for (e=1;e<=n;e++){                             // declare matrix b
        for(r=1;r<=k;r++){
            scanf("%d",&b[e][r]);  
        }
    }
    for (c=1;c<=m;c++){                              // multipication of a and b
        for (v=1;v<=k;v++){
            for (x=1;x<=n;x++){
                z[c][v]+=a[c][x]*b[x][v];
            }
            printf("%d ",z[c][v]);
            x=1;
        }
        v=1;
        printf("\n");
    }
    return 0;
}
Đức
  • 1
  • 1
  • 2
    A little OT, but this is not 1970; you *really* need to work on your variable names. – Mark Benningfield Dec 18 '22 at 04:46
  • Have a look at this https://www.javatpoint.com/matrix-multiplication-in-c – Srikanth Dec 18 '22 at 04:48
  • 5
    Arrays in C are indexed from 0 to size-1. When you declare `int T[5];`, you declare an array containing `T[0]`, `T[1]`, `T[2]`, `T[3]`, `T[4]`. But no `T[5]`. – chrslg Dec 18 '22 at 04:50
  • you need to change all your `=1` to `=0` and all your `<=` to `<`, at least. – yano Dec 18 '22 at 05:14
  • 1
    Why are you passing the addresses of `const int` variables to `scanf`? I'm more of a C++ than C guy, but pretty sure that's not legal. – Stephen Newell Dec 18 '22 at 05:39
  • 2
    `z[c][v]+=...` increments `z[c][v]`, but there is nothing in your code that ever sets it to zero. C doesn't do that for you. The initial values of the array elements can be anything. – Gene Dec 18 '22 at 05:45

0 Answers0