您的功能create_matrix
應該返回m
而不是將其作爲參數。
由於編碼,功能create_matrix
做分配,但指針是一個本地變量,並在函數返回時丟失。
您還應該檢查fscanf()
和malloc()
的返回值,以正確檢測並處理故障。
您還應該在使用後釋放分配的對象。
這裏是你的代碼的修正版本:
的main.c:
#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;
}
library.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);
LIBRARY.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;
}
爲什麼你讀它作爲雙打? –
什麼是'm'?什麼是值或'r'和'c'?你怎麼稱呼這個功能?你如何打印這些值?你可以試着創建一個[最小,***完整***和可驗證示例](http://stackoverflow.com/help/mcve)並向我們展示? –
m是te矩陣,r是行數,c是列數。我打電話給這個函數:'fill_matrix(matrix,rows,columns,argv [1]);' 要打印這些值:'fprintf(temp_file,「%lf」,m [i] [j] );' –