c - How to dynamically allocate memory in 2D array and store values? -
i trying allocate memory in 2d array dynamically, don't know wrong.
error
let input is
2 2 1 2 3 4 5 6 7 8 9 ........ then program crashes
#include<stdio.h> #include<stdlib.h> int main() { int n,m; int i,j; scanf("%d %d",&n,&n); int **a = (int **)malloc(n*sizeof(int *)); for(i=0;i<n;i++) { a[i] = (int *)malloc(m*sizeof(int)); } for(i=0;i<n;i++) { for(j=0;j<m;j++) { scanf("%d",&a[i][j]); } } for(i=0;i<n;i++) { for(j=0;j<m;j++) { printf("%d",a[i][j]); } } return 0; }
as said problem in scanning n , m variables.
change
scanf("%d %d",&n,&n); to
scanf("%d",&n); scanf("%d",&m); and fine.
problem reading n twice while didnt read m used uninitialized.
non-static variables (local variables) indeterminate. reading them prior assigning value results in undefined behavior.
you should free allocated memory
for(i=0;i<n;i++) { free(a[i]); } free(a); and dont cast malloc()'s return value becouse
- its reduntand
- adding cast may mask failure include header
stdlib.h, in prototype malloc found - if type of pointer changed, 1 must fix code lines
malloc()called , cast
next time if cannot find bug, try use debugger , happening, can see variable values, see m uninitialized , didnt change after scanf().
Comments
Post a Comment