【发布时间】:2021-12-15 18:16:19
【问题描述】:
我写了两个函数,readMatrix 分配一个双指针并从键盘获取输入,第二个函数是打印函数。
当我在主函数中调用打印函数时,它并没有完全起作用。
这是代码:
void print(int** mat, int lin, int col) {
int i,j;
printf("Matrix is:\n");
for(i=0; i<lin; i++) {
for(j=0; j<col; j++) {
printf("%d ", *(*(mat+i)+j));
}
printf("\n");
}
}
int** readMatrix(int** mat, int lin, int col) {
int x;
int i,j;
mat==(int**)malloc(lin*sizeof(int*));
for(x=0; x<lin; x++) {
mat[x]=(int*)malloc(col*sizeof(int));
}
for(i=0; i<lin; i++) {
printf("Line %d: ", i);
for(j=0; j<col; j++) {
scanf("%d", &mat[i][j]);
}
}
}
int main()
{
int lin, col;
int i,j;
printf("Enter number of lines: ");
scanf("%d", &lin);
printf("Enter number of cols: ");
scanf("%d", &col);
int** mat = readMatrix(mat,lin,col);
print(mat,lin,col);
return 0;
}
输入后,我得到消息“矩阵是”,但矩阵没有出现,为什么?
如果我在 readMatrix 函数中调用 print 函数,它可以工作,但如果我在 main 中调用它为什么不工作?
谢谢。
【问题讨论】:
-
关于:
mat==(int**)malloc(lin*sizeof(int*));和类似的语句:1)返回的类型(在 C 中)是void*,可以分配给任何指针。强制转换只会使代码混乱并且容易出错。 2) 对于健壮的代码,始终检查 (!=NULL) 返回值以确保操作成功
标签: c pointers multidimensional-array malloc dynamic-memory-allocation