这个函数的输入应该是一对整数,即矩阵的
size
,紧随其后是col*row
个整数。它看起来像这样:2 3
76 98 -31
30 30 32
这是我目前编写的代码,对于行和列大小来说它可以正常运行,但是当我尝试传递指向读取矩阵的指针时,它会崩溃。我对如何将 int** matrix
参数传递到函数中感到困惑。(在讲座上我看到了一个类似的函数示例,所以我更喜欢使用双指针的解决方案。
#include <stdio.h>
#include <stdlib.h>
int load_matrix(int *ro,int *co, int **matrix);
int main(int argc, char* argv[]) {
int row = 3;
int col = 3;
int *ro = &row;
int *co = &col;
//int matx[1];
int **matrix; //= matx[0];
load_matrix(ro,co,matrix);
}
int load_matrix(int* ro,int* co, int** matrix) {
int rows, cols;
if(scanf("%d %d",&rows,&cols)==2) {
int *mat = malloc(sizeof(int)*rows*cols);
int read=0;
for(int i = 0; i<rows &&read>=0; i++) {
for(int j = 0; j<cols && read >=0; j++) {
if(scanf("%d", &(mat[i*cols+j]))!=1) {
read = -1;
} else {
read++;
}
}
}
if(read == (rows*cols)) {
*ro = rows;
*co = cols;
**matrix = mat; --- this crashes the program
} else {
free(mat);
*matrix = 0;
}
} else {
return 100;
}
return 0;
}
在代码中标记的部分,当我尝试将指针int ** matrix
分配给读取矩阵分配的地址的新值时,它会崩溃。我应该如何处理这些指针?