[英]Reading a file to matrix in C
I get我得到
"Debug assertion failed"
“调试断言失败”
error when I try to compile this code.当我尝试编译此代码时出错。
Can someone please explain what is wrong with it?有人可以解释一下它有什么问题吗? I think I've done something wrong with fscanf function.
我想我在 fscanf 函数上做错了。 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 are several issues here, but to directly answer your question, you are not providing an address to fscanf()
where it will store the integer it finds.这里有几个问题,但要直接回答您的问题,您没有向
fscanf()
提供地址,它将存储它找到的整数。
Without knowing your intent, I'll give an example:不知道你的意图,我举个例子:
fscanf( fp, "%d\n", &(a[i]) );
That says the ith
element of array a
is the one to be (over)written.也就是说数组
a
的ith
元素是要(覆盖)写入的元素。 So if a[i]
is an int pointer, you might pass &( (a[i])[j] ) in there.所以如果
a[i]
是一个 int 指针,你可能会在那里传递 &( (a[i])[j] ) 。
Also, I think you meant to replace:另外,我认为您打算替换:
*(a+i)=(int*)malloc(m*sizeof(int));
with和
a[i] = (int*) malloc(m*sizeof(int));
The other comments and answers already pointed out what is not ok.其他评论和答案已经指出了什么是不对的。 So I skip it (
fscanf(...)
, free
, etc.).所以我跳过它(
fscanf(...)
, free
等)。
The corrected version.修正后的版本。
#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");
}
for (i = 0; i < m; i++)
free(a[i]);
free(a);
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.