我尝试使用函数读取包含矩阵 [n]x[m] 值的 .txt 文件,然后在我的 main 中调用它,但我遇到了一些问题...这是读取函数:
bool read_file(int row, int column, char *file_name, float **elems)
{
int i, j;
FILE *pfile;
fopen_s(&pfile, file_name, "r");
if (pfile == NULL) {
return false;
}
fscanf_s(pfile, "%d", &row);
fscanf_s(pfile, "%d", &column);
//printf_s("%d %d\n", row,column);
for (i = 0; i < row; i++)
{
for (j = 0; j < column; j++) {
fscanf_s(pfile, "%f", &elems[i][j]);
//printf("%f\n", elems[i][j]);
}
}return true;
}
我的程序要求我在两个矩阵之间进行乘积,我必须通过两种类型的输入(键盘或文件)来完成。我在主要的 if-else 中使用了两个输入之间的选择。当它进行键盘输入时,一切正常(动态分配以及矩阵乘积都可以工作)。然后我在 main 中调用这样的函数:
int main(){
int i, j, row1, column1, row2, column2;
char* file_name1 = { "C:\\Users\\Lc\\Documents\\Matrix1.txt" };
char* file_name2 = { "C:\\Users\\Lc\\Documents\\Matrix2.txt" };
if (...) {
...
/* Input by keybord. */
...
}
else if(...){ /*Input by file*/
read_file(row1, column1, file_name1, matrix1);
read_file(row2, column2, file_name2, matrix2);
...
}
...
然后它说矩阵1和矩阵2未定义...我明白为什么它们未定义,但我的问题是我不知道如何像使用键盘输入那样定义它们
最佳答案
float **elems
是一个指向 float 数组的指针数组的指针。您可以通过在循环中调用 malloc() 来创建这样的东西。
注意它在代码中的使用方式:
fscanf_s(pfile, "%f", &elems[i][j]);
因此 elems[0..N]
旨在指向行。首先,分配外部数组:
float** elems = malloc(row * sizeof(float*));
assert(elems);
每一行都有一个float*
。然后,分配每一行:
for (i = 0; i < row; i++)
{
elems[i] = malloc(column * sizeof(float));
assert(elems[i]);
}
现在,elems
指向一个 float*
数组,每个元素都指向一个 float
数组(其中数字未初始化)。
关于c++ - 使用函数读取文件.txt中的矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43948568/