Search code examples
cmultidimensional-arraymatrix-multiplication

Could someone please point out the error in my code


#include<stdio.h>
int main()
{
    setbuf(stdout,NULL);
    int p,q,r,s,a[p][q],b[r][s],i,j,k,u,v,res[u][v],sum=0;
    printf("Enter the number of rows and columns of the 1st matrix: ");
    scanf ("%d%d",&p,&q);
    printf("Enter the number of rows and columns of the 2nd matrix: ");
    scanf ("%d%d",&r,&s);
    printf("Enter the elements of matrix1: ");
    u=p;
    v=s;
    for(i=0;i<p;i++)
    {
        for(j=0;j<q;j++)
        {
            scanf("%d",&a[i][j]);
        }
    }
    printf("Enter the elements of matrix2: ");
    for(i=0;i<r;i++)
    {
        for(j=0;j<s;j++)
        {
            scanf("%d",&b[i][j]);
        }
    }
    for(i=0;i<p;i++)
    {
        for(j=0;j<s;j++)
        {
            for(k=0;k<r;k++)
            {
                sum+=a[i][k]*b[k][j];
            }
            res[i][j]=sum;
            sum=0;
        }
    }
    printf("The resultant matrix is: ");
    for(i=0;i<p;i++)
    {
        for(j=0;j<s;j++)
        {
            printf("%d\t",res[i][j]);
        }
        printf("\n");
    }
return 0;
}

**I'm trying to write a program to perform Matrix Multiplication. The code isn't getting executed...its just terminating and I really cant find the error. When I tried running it online I got ''Bus error(Code Dumped)error 135"...but in my system the programs just terminating without an error. Please help me find the mistake or concept I'm missing here.. **


Solution

  • In the code

     int p,q,r,s,a[p][q],b[r][s],i,j,k,u,v,res[u][v],sum=0;
    

    you are using the values of p, q, r, s, u and v uninitialized. As they have automatic storage (local scope) and the type int can have trap representation, and the variables u and v never have their address taken, it'll invoke undefined behaviour. Even for the other variables other than u and v, the values will be indeterminate, resulting in practically invalid code.

    To resolve the problem, define the VLAs after you scan the values into the respective variables to be used as array dimension.