【发布时间】:2015-06-18 22:20:00
【问题描述】:
我一直在为我的大学编写代码,在那里我们使用矩阵,但我在代码中找不到更改我保存矩阵列的变量值的错误。我已经尝试调试它但找不到它,它只是结束了我为矩阵分配内存的函数,并使用错误的列值进入下一个函数(从键盘获取值以填充矩阵)。 代码如下:
#include <stdio.h>
#include <stdlib.h>
#define DEBUG 1
void allocate (int ***mat,int n,int m){
int i;
*mat = (int **) malloc (n*sizeof(int*));
for (i=0; i<n; i++){
mat[i] = (int *) malloc (m*sizeof(int));
}
#if DEBUG
printf ("allocate n: %d m: %d\n",n,m);
#endif // DEBUG
}
void initialize (int **mat, int n, int m){
int i,j;
#if DEBUG
printf ("initialize n: %d m: %d\n",n,m);
#endif // DEBUG
for (i=0; i<n; i++){
for (j=0; j<m; j++){
printf ("Enter value for position [%d][%d]: ",i,j);
scanf ("%d",&(mat[i][j]));
}
}
}
int main()
{
int n=2;
int m=3;
int **mat=NULL;
#if DEBUG
printf ("before allocate n: %d m: %d\n",n,m);
#endif // DEBUG
allocate (&mat,n,m);
#if DEBUG
printf ("after allocate n: %d m: %d\n",n,m);
#endif // DEBUG
initialize (mat,n,m);
return 0;
}
因此,如果您在 DEBUG 设置为 1 的情况下运行此程序,您将获得 n 和 m 的值(这是我的行和列)。我正在使用代码块。 感谢您的宝贵时间!
【问题讨论】:
-
你能提供一个示例输出吗?
-
发布实际编译的代码。也修复警告。
-
您需要将分配更改为
(*mat)[i] = (int *) malloc (m*sizeof(int)); -
@ooga:是的,他有。但这不会导致他正在谈论的问题,因为那根本无法编译。
-
编译后(修复分配,函数调用中的拼写错误
initialize和缺少分号),代码对我有用,我看不出有任何原因t.