问题
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?
回答1:
Could anyone explain what I am doing wrong?
You are returning a pointer to a local/automatic storage duration structure which is not guaranteed to exist beyond the scope { } of the function.
There are a number of ways to do this. The aim is return a structure which remains alive and active even after returning from the function.
The more commonly used way to do this is to allocate the structure dynamically, populate it and return a pointer to it.
struct maze* init_maze(int row, int column)
{
struct maze *pmazeFilled = malloc(sizeof(*pmazeFilled));
pmazeFilled->row = row;
pmazeFilled ->column = column;
return pmazeFilled;
}
Remember the caller must free the allocated memory by calling free on the returned pointer.
来源:https://stackoverflow.com/questions/15038193/initializing-an-variable-matrix-in-a-structure-c