将文件中的值加载到2D数组指针的值中 [英] Load value from file to a value of 2D array pointer
问题描述
如何在另一个函数中将文件中的值正确加载到矩阵中?
How do I correctly load the values from file to the matrix in another function?
void someFunction(int ***matrix, n, m) {
int c, d;
FILE *fp = fopen("some.txt", "r"); // načtení souboru
for (c = 0; c < m; c++) {
for (d = 0; d < n; d++) {
fscanf(fp, "%i", &matrix[c][d]); //4th read throws error
}
}
}
int main() {
int i;
int **matrix;
int n = 3; // columns
int m = 2; // rows
first = (int **)malloc(n * sizeof(int*));
for (i = 0; i < n; i++)
first[i] = (int *)malloc(m * sizeof(int));
someFunction(&matrix, n, m);
free(matrix);
for (i = 0; i < n; i++)
free(first[i]);
}
fscanf(fp, "%i", &matice[c][d])
对吗?
它在[1][0]
处失败(内存错误),但[0][0],[0][1],[0][2]
可以正常工作.我不确定自己做错了什么.
It fails (memory error) at [1][0]
but [0][0],[0][1],[0][2]
works fine. I am not sure what I did wrong.
推荐答案
您有一个指针数组,每个元素都设置为指向动态分配的块.这不是2D数组,尽管您可以使用与2D数组相同的语法对整个数据结构进行索引.
You have an array of pointers, each element set to point to a dynamically-allocated block. This is not a 2D array, though you can index into the overall data structure via the same syntax that you would use for a 2D array.
您至少有两个问题:
-
根据您的分配策略,数组的第一个索引从
0
到n - 1
,指向指针的数组的索引从0
到m - 1
.在n
和m
不同的情况下,您可以在读取循环中反转该值,从而超出至少一个数组的边界.
By your allocation strategy, the first index of your array runs from
0
ton - 1
, and the indexes into the pointed-to arrays run from0
tom - 1
. You reverse that in your read loop, thereby overrunning the bounds of at least one of your arrays ifn
andm
differ.
更重要的是,您传递给fscanf()
的存储指针是错误的.在someFunction()
中,变量matrix
的类型为int ***
,并且您传递了int **的地址.因此,索引为[c
] [d
]的元素为(*matrix)[c][d]
,该元素的地址为&(*matrix)[c][d]
,它与&matrix[c][d]
完全不同,甚至与matrix[c][d]
.
More significantly, the storage pointer you pass to fscanf()
is wrong. In someFunction()
, variable matrix
has type int ***
, and you pass an address of your int **. The element at index [c
][d
] is therefore (*matrix)[c][d]
, and the address of that element is &(*matrix)[c][d]
, which is not at all the same thing as &matrix[c][d]
, nor even the same as matrix[c][d]
.
这篇关于将文件中的值加载到2D数组指针的值中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!