【发布时间】:2017-11-10 05:26:02
【问题描述】:
我正在尝试使用fscanf 从文本文件中读取 NxN 矩阵和 1xN 矩阵的数字。我知道这个问题以前在这里被问过,但我已经尝试了解决方案,但根本无法理解为什么我的方法不起作用。 NxN 矩阵为:
1 1 1
3 1 0
-1 0 1
1xN 矩阵为:
6
11
-2
行中的数字用一个空格分隔,列中用\n 分隔。这是我的代码:
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
int countlines(FILE *f);
void reduce_mat(double **matrix, double *vector, int row, int column);
void swapping(double **matrix, double *vector, int row, int column);
int main()
{
FILE *f1=fopen("matrix.txt","r");
FILE *f2=fopen("vector.txt","r");
int dim_matrix=countlines(f1);
int dim_vector=countlines(f2);
//allocate memory for matrix and vector
double **Mat_A=(double **) malloc(dim_matrix*sizeof(double));
for(int j=0; j<dim_matrix; j++)
Mat_A[j]=(double *) malloc(dim_matrix*sizeof(double));
double *Vec_B=(double *) malloc(dim_vector*sizeof(double));
//read in numbers from file
for(int i=0; i<dim_matrix; i++)
for(int j=0; j<dim_matrix; j++)
{
fscanf(f1,"%lf",&Mat_A[i][j]);
printf("Mat_A[%d][%d]=%lf\n",i,j,Mat_A[i][j]);
}
for(int k=0; k<dim_vector; k++)
{
fscanf(f2, "%lf", &Vec_B[k]);
printf("Vec_B[%d]=%lf\n",k,Vec_B[k]);
}
int countlines(FILE *f)
{
//check if file exists
if (f==NULL)
{
printf("File does not exist");
return 0;
}
int count=0; //intialize the count
char c; //place to store characters from file
for (c=getc(f); c!=EOF; c=getc(f))
{
if (c=='\n')
{
count+=1;
}
}
return count;
}
它只是为每个值打印出零。我曾尝试使用"%lf%[\n]%"、"%lf%" 等。我根本不知道哪里出错了,因为这个实现似乎对其他人有用。
【问题讨论】:
-
检查
fopen和malloc的返回值。 -
double **Mat_A=(double **) malloc(dim_matrix*sizeof(double));可能是错误的大小分配。使用double **Mat_A= malloc(sizeof *Mat_A * dim_matrix);分配正确的大小。 -
并检查
fscanf的返回值。即使它可能有效,这在语义上也是错误的:double **Mat_A=(double **) malloc(dim_matrix*sizeof(double));。你想要sizeof(double *) -
不要转换
malloc的返回值 -
是的,你没看错。您必须“在 j 上的 for 循环内”进行分配,以便为每个数组分配内存。但是你的教授关于转换 malloc 的返回值是错误的。在 C 中没有必要。stackoverflow.com/questions/605845/…
标签: c file matrix double scanf