Display 2D array using pointers and function in c -
this question has answer here:
respected members of stackoverflow, complete armature c program,i want access element of matrix using pointers.like want print elements of matrix using point.i have attached code along incorrect output.please me .thank you
` #include<stdio.h> #include<conio.h> void print(int **arr, int m, int n) { int i, j; (i = 0; < m; i++) { (j = 0; j < n; j++) { printf("%d ",*(arr+i*n+j)); //print elements of 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 matrix without function calling { for(d=0;d<n;d++) { printf("%d ",arr[c][d]); } printf("\n"); } print((int **)arr, m, n); //print matrix using function calling getch(); return 0; }`
above code produce output shown below
row= 2 col= 3 //elements of 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 not getting exact matrix value. note:print(int **a,int m,int n) should used.
as @whozcraig told in coment, arr
should int**
int** arr = malloc(sizeof(int*)*m); int a; for(a=0;a<m;a++) arr[a]=malloc(sizeof(int)*n); for(c=0;c<m;c++) { for(d=0;d<n;d++) { scanf("%d", &arr[c][d]); //scanf("%d",arr+c*n+d); } }
note: not tested
edit: malloc not casted
Comments
Post a Comment