0

I am getting wrong output while using function pointer.addition of 2 matrix!!

having wrong outputs while using function pointers. CODE: #include<stdio.h> int r,c; void add(int a1[r][c],int b1[r][c],int k,int l) { int result[k][l];int i,j; for(i=0;i<k;i++) { for(j=0;j<l;j++) { result[i][j]=a1[i][j]+b1[i][j]; //return result[i][j]; printf("%d\t",result[i][j]); } printf("\n"); result[i+1][j+1]=0; } } int main() { int r,c,i,j; printf("enter row and column\n"); scanf("%d%d",&r,&c); int a[r][c],b[r][c]; printf("enter matrix 1\n"); for(i=0;i<r;i++) { for(j=0;j<c;j++) { scanf("%d",&a[i][j]); } } printf("enter matrix 2\n"); for(i=0;i<r;i++) { for(j=0;j<c;j++) { scanf("%d",&b[i][j]); } } void(*f)(int,int,int,int)=&add; f(a,b,r,c); return 0; } input: rows = 2 columns = 2 1st matrix: 1 1 2 2 2nd matrix: 1 1 2 2 output: 2 2 2 2 getting trouble in 2nd row.

24th Apr 2021, 8:20 AM
Sahil Jain
Sahil Jain - avatar
1 ответ
+ 1
You defined r, c twice (global and main scope) and r, c are unknown for add function (garbage values), you have to specify "c" when passing 2D array to the function, or just pass double pointer instead, so there will be no need of specifying number of columns or rows
24th Apr 2021, 8:39 AM
Michal Doruch