Error while calculating sum of two matrices in c -
so i'm new c , trying write program add 2 matrices
program 1
#include <stdio.h> int main(){ int m,n,o,p,i,j; int mat1[m][n]; int mat2[m][n]; int result[m][n]; printf("enter number of rows , columns matrix "); scanf("%i%i",&m,&n); printf("enter elements of matrix 1 :"); for(i=0;i<m;i++){ for(j=0;j<n;j++){ scanf("%i",&mat1[i][j]); } } printf("enter elements of matrix two:"); for(i=0;i<m;i++){ for(j=0;j<n;j++){ scanf("%i",&mat2[i][j]); } } for(i=0;i<m;i++){ for(j=0;j<n;j++){ result[i][j]=mat1[i][j]+mat2[i][j]; } } printf("the sum of matrices are"); for(i=0;i<m;i++){ for(j=0;j<n;j++){ printf("%i",result[i][j]); } } return 0; } this produced no error
method two
when used function enter values in 2 matrix, produced following error
25 24 c:\users\hp\my-programs\matrix-entry-function.cpp [error] invalid types 'int[int]' array subscript 25 35 c:\users\hp\my-programs\matrix-entry-function.cpp [error] invalid types 'int[int]' array subscript code:
#include <stdio.h> int mat_entry(int m,int n) { printf("enter rows , columns of matrix "); scanf("%i%i",&m,&n); int mat[m][n]; for(int i=0;i<m;i++) { for(int j=0;j<n;j++) { printf("\nenter %i'th element %i'th row :",j+1,i+1); scanf("%i",&mat[i][j]); } } } int main() { int a,b,c,d,e,f,m,n; int res[m][n]; int mat1=mat_entry(a,b); int mat2=mat_entry(c,d); for(int i=0;i<m;i++) { for(int j=0;j<n;j++) { res[i][j]=(mat1[i][j]+mat2[i][j]); } } }
your program 1 happened not produce error. unlucky. invoked undefined behavior using values in uninitialized variables having automatic storage duration, indeterminate. must declare mat1, mat2 , result after reading m , n.
int main(){ int m,n,o,p,i,j; printf("enter number of rows , columns matrix "); scanf("%i%i",&m,&n); /* move these declaretions after reading number of rows , columns */ int mat1[m][n]; int mat2[m][n]; int result[m][n]; printf("enter elements of matrix 1 :"); your program 2 invokes undefined behavior using return values of functions no return statements. using [] operator 2 operands having type int wrong. e1[e2] equivalent (*((e1)+(e2))) (n1570 6.5.2.1 array subscripting, paragraph 2), 1 operand of must pointer (including 1 converted arrays).
to return matrixes return values of functions, consider using structures , allocating memory elements dinamically.
Comments
Post a Comment