我用 C 写了这个函数:
void fill_matrix(double **m, int r, int c, char *file) {
int i, j;
FILE *temp_file = fopen(file, "r");
for (i = 0; i < r; i++) {
for (j = 0; j < c; j++) {
fscanf(temp_file, "%lf", &m[i][j]);
}
}
fclose(temp_file);
}
矩阵是这样定义和分配的:
double **m;
m = (double **)malloc(r * sizeof(double *));
for (i = 0; i < r; i++)
m[i] = (double *)malloc(c * sizeof(double));
r
和c
是行数和列数。
参数是:
fill_matrix(m, r, c, filename);
在testin.txt文件中,我有这个矩阵:
1 2 3 4
5 6 7 8
9 1 2 3
但我的输出是:
1.00 0.00 0.00 0.00
5.00 6.00 0.00 0.00
9.00 1.00 2.00 3.00
你能告诉我如何解决这个问题吗?谢谢你的时间。
您的函数create_matrix
应该返回m
而不是将其作为参数。
按照编码,该函数create_matrix
进行分配,但指针是一个局部变量,并在函数返回时丢失。
您也应该检查返回值fscanf()
,并malloc()
能正确检测并处理故障。
您还应该在使用后释放分配的对象。
这是您的代码的更正版本:
主文件:
#include <stdio.h>
#include "library.h"
int main(void) {
int rows, columns;
// Take the order matrix
printf("Number of rows: ");
if (scanf("%d", &rows) != 1)
return 1;
printf("Number of columns: ");
if (scanf("%d", &columns) != 1)
return 1;
matrix = create_matrix(rows, columns);
if (matrix != NULL) {
if (!fill_matrix(matrix, rows, columns, "testin.txt")) {
print_matrix(matrix, rows, columns, "testout.txt");
}
free_matrix(matrix, rows, cols);
}
return 0;
}
图书馆.h
double **create_matrix(int r, int c);
void free_matrix(double **m, int r, int c);
int fill_matrix(double **m, int r, int c, const char *file);
int print_matrix(double **m, int r, int c, const char *file);
图书馆.c
#include <stdio.h>
#include <stdlib.h>
#include "library.h"
double **create_matrix(int r, int c) {
int i;
double **m = malloc(r * sizeof(*m));
if (m != NULL) {
for (i = 0; i < r; i++) {
m[i] = malloc(c * sizeof(*m[i]));
if (m[i]) == NULL) {
while (i-- > 0) {
free(m[i]);
}
free(m);
return NULL;
}
}
}
return m;
}
void free_matrix(double **m, int r, int c) {
int i;
if (m) {
for (i = 0; i < r; i++) {
free(m[i]);
}
free(m);
}
}
int fill_matrix(double **m, int r, int c, const char *file) {
int i, j;
FILE *temp_file = fopen(file, "r");
if (temp_file == NULL)
return -1;
for (i = 0; i < r; i++) {
for (j = 0; j < c; j++) {
if (fscanf(temp_file, "%lf", &m[i][j]) != 1) {
fclose(temp_file);
return -1;
}
}
}
fclose(temp_file);
return 0;
}
int print_matrix(double **m, int r, int c, const char *file) {
int i, j;
FILE *temp_file = fopen(file, "w");
if (temp_file == NULL)
return -1;
for (i = 0; i < r; i++) {
for (j = 0; j < c; j++) {
fprintf(temp_file, "%f%c", m[i][j], " \n"[j == c - 1]);
}
}
fclose(temp_file);
return 0;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句