Respected members of stackoverflow, Am a complete armature to c program,I want to access the element of the matrix using pointers.like i want to print the elements of the matrix using point.I have attached the code along with the incorrect output.please help me .thank you
`
#include<stdio.h>
#include<conio.h>
void print(int **arr, int m, int n)
{
int i, j;
for (i = 0; i < m; i++)
{
for (j = 0; j < n; j++)
{
printf("%d ",*(arr+i*n+j)); //print the elements of the matrix
//printf("%d ", *((arr+i*n) + j));
}
printf("\n");
}
}
int main()
{
int arr[20][20],m,n,c,d;
clrscr();
printf("row=\n");
scanf("%d",&m);
printf("col=\n");
scanf("%d",&n);
for(c=0;c<m;c++)
{
for(d=0;d<n;d++)
{
scanf("%d",&arr[c][d]);
}
}
for(c=0;c<m;c++) //print the matrix without function calling
{
for(d=0;d<n;d++)
{
printf("%d ",arr[c][d]);
}
printf("\n");
}
print((int **)arr, m, n); //print the matrix using function calling
getch();
return 0;
}`
above code produce the output shown below
row=
2
col=
3
//elements of the matrix
2
3
4
5
6
7
//print without using function
2 3 4
5 6 7
//print using function"print(int **a,int m,int n)"
2 3 4
0 0 0
when using function am not getting the exact matrix value. NOTE:print(int **a,int m,int n) should be used.
int arr[20][20]is notint**, and the compiler failing unless you forcibly make that cast should be an indicator that something is wrong.int,int**, is not synonymous to a pointer toint[20], i.e.int (*)[20], which is what you're argument expresses to be. Removing the cast and attempting to compile should tell you in-as-much the same thing I just did. A cast isn't the solution to "fix" that error.printf("%d ",*(arr+i*n+j));change toprintf("%d ", arr[i][j]);(for maskacovnik's answer)