I am having trouble with initializing a variable matrix in a structure in C. Have been reading a couple of posts(post) but I cant seem to fix it. Don't ask me why but for an assignment I need to initialize a matrix located in a structure.
My code for the struct is:
typedef struct maze{
int row;
int column;
char matrix[row][column];
}maze;
By calling a different function, after reading a certain file, I need to initialize a matrix by its given parameters, so 2 parameters "row" and "column".
My code for the init function is:
struct maze* init_maze(int row, int column) {
struct maze mazeFilled;
struct maze *mazePointer;
mazeFilled.row = row;
mazeFilled.column = column;
return mazePointer;
}
But as you can guess this is not working, people already mentioned that it is hard to create a matrix from 2 variables. Could anyone explain what I am doing wrong.
EDIT 1:
I changed my code according to the posts the struct however remains the same. I needed to allocate the pointer so it even stays active outside the scoop.
My new code for the init funct is:
struct maze* init_maze(void) {
int row = 6;
int column = 10;
struct maze *mazePointer = malloc(sizeof (*mazePointer));
mazePointer->row = row;
mazePointer->column = column;
return mazePointer;
}
EDIT 2:
Think I discoverd what my error was, I did not allocate memory for the matrix. My new init function:
struct maze* init_maze(void) {
int row = 6;
int column = 10;
maze *mazePointer;
mazePointer = malloc(sizeof(maze));
mazePointer->row = row;
mazePointer->column = column;
mazePointer->matrix = malloc(row * sizeof(char*));
for (int i; i < row; i++) {
for(int j; j < column; j++) {
mazePointer -> matrix[i][j] = malloc(1 * sizeof(char*));
}
}
return mazePointer;
}
I am still not sure how to allocate the memory for just the first array, [i]. Could anyone tell me if I am in the right direction?