【发布时间】:2020-01-29 02:50:50
【问题描述】:
我正在尝试打开一个包含两个矩阵的维度和值的文件。我想存储矩阵的维度,并使用从文件中读取的维度创建三个 2D int 数组(第三个是矩阵乘法的结果)。我正在传递一个指向参数的 int 指针的指针,因此 read_matrices 方法的参数是 int**(赋值要求)。
我在代码的 malloc 部分中不断遇到分段错误,但无法找出问题所在。它似乎适用于前两个矩阵,我可以在 array3 的 malloc 期间打印第一个 printf 语句,但在第二个 printf 语句之前出现分段错误。我认为循环中有问题,但我无法弄清楚,特别是因为它似乎适用于 array1 和 array2 的 malloc (除非整个事情都是错误的)。任何帮助表示赞赏。
编辑:编辑为仅包含代码中最重要的部分
void read_matrices(int **array1, int **array2, int **array3, int *m, int *n, int *p, char* file)
{
/* Get the size of the matrices */
fscanf(fp, "%d", m);
fscanf(fp, "%d", n);
fscanf(fp, "%d", p);
/* Use malloc to allocate memory for matrices/arrays A, B, and C */
array1 = (int**) malloc(*m * (sizeof(int*)));
for (i = 0; i < *m; i++)
{
*(array1 + i) = (int*) malloc(*n * (sizeof(int)));
}
array2 = (int**) malloc(*n * (sizeof(int*)));
for (i= 0; i < *n; i++)
{
*(array2 + i) = (int*) malloc(*p * (sizeof(int)));
}
array3 = (int** ) malloc(*m * (sizeof(int*)));
for (i= 0; i < *m; i++)
{
*(array3 + i) = (int *) malloc(*p * (sizeof(int)));
printf("Going through malloc3 loop\n");
}
printf("End of the third part of malloc\b");
/* Close the stream */
fclose(fp);
}
int main (int argc, char *argv[])
{
/* Int pointers to three matrices */
int *A, *B, *C;
/* Int variables to store matrix dimensions */
int m, n, p;
/* Get the name of the file */
char* filename = *(argv + 1);
/* Read the matrices and fill matrices A and B */
read_matrices(&A, &B, &C, &m, &n, &p, filename);
/* Exit the system */
return 0;
}
【问题讨论】:
-
由于stackoverflow.com/q/1398307/1848654 / stackoverflow.com/q/766893/1848654,您的
mult_matrices(A, B, C, m, n, p)调用具有未定义的行为。 -
所以我有点困惑。我认为对于 2D 数组,我可以在 main 中将其定义为 int*,使用 & 运算符通过引用传递,然后在 read_matrices 方法中将其作为指针接收。我是在 main 中错误地定义了 2D 数组,还是我使用 malloc 的方式?对不起!我对 C 很陌生
-
这段代码甚至无法编译。因此它不会产生分段错误。
-
您是否阅读了链接的问题和答案?
标签: c multidimensional-array segmentation-fault malloc