Reading a file to matrix in C -
i
"debug assertion failed"
error when try compile code.
can please explain wrong it? think i've done wrong fscanf function. thank you.
#include<stdio.h> #include<stdlib.h> #include<malloc.h> void input(file *fp, int **a,int m) { int i,j; for(i=0;i<m;i++) { for(j=0;j<m;j++) { fscanf(fp, "%d\n", *(a+i)+j); } } } int main() { file*fp; int m,n,**a,i,j; scanf("%d",&m); fp=fopen("abc.txt","r"); a=(int**)malloc(m*sizeof(int*)); for(i=0;i<m;i++) *(a+i)=(int*)malloc(m*sizeof(int)); input(fp,a,m); for(i=0;i<m;i++) { for(j=0;j<m;j++) { printf("%d ",*((a+i)+j)); } printf("\n"); } free(a); return 0; }
there several issues here, directly answer question, not providing address fscanf()
store integer finds.
without knowing intent, i'll give example:
fscanf( fp, "%d\n", &(a[i]) );
that says ith
element of array a
1 (over)written. if a[i]
int pointer, might pass &( (a[i])[j] ) in there.
also, think meant replace:
*(a+i)=(int*)malloc(m*sizeof(int));
with
a[i] = (int*) malloc(m*sizeof(int));
Comments
Post a Comment