The input to this function is supposed to be a pair of integers - size
of matrix - followed by col*row
integers. It looks something like this
2 3
76 98 -31
30 30 32
This is the code I've written so far. It works for row and column sizes but when I try to pass pointer to the read matrix, it crashes. I'm confused about how I'm supposed to pass the int** matrix
argument into the function. (I've seen an example of similar function at the lecture, so I'd prefer a solution using the double pointer.
#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;
}
As marked in the code, the part where it crashes is when I try to assign the pointer int** matrix
a new value to the address where the read matrix is allocated. How am I supposed to work with the pointers here?