在不知道结构大小的情况下在结构中声明二维数组?
Declaring a 2D array in a struct without knowing the size in a struct?
我可以在 C 中执行此操作吗?
我的代码出现错误
ERROR
minesweeper.c:19:19: error: expected ‘:’, ‘,’, ‘;’, ‘}’ or ‘__attribute__’ before ‘=’ token
int *boardSpaces = (int *)malloc(newBoard.rows * newBoard.columns * sizeof(int));
typedef struct boards
{
int rows, columns;
int *boardSpaces = malloc(rows * columns * sizeof(int));
} Board;
但是当我把它放在我的 main 中时它工作得很好。
我可以在结构中声明它吗,还是我遗漏了什么?
你不能运行像那样对结构中的变量起作用。
简短的回答是因为 rows
和 columns
在编译时没有任何价值。
你可以这样做,在这个函数中,create_board和delete_board本质上是模仿c++的构造函数和析构函数,但你必须手动调用它们。
struct Board
{
int rows, columns;
int *boardSpaces; // memory will be allocated when we need it
};
/* create a board with a given size, as memory is dynamically allocated, it must be freed when we are done */
struct Board createBoard(int rows, int columns){
struct Board b;
b.rows = rows;
b.columns = columns;
b.boardSpaces = malloc(rows * columns * sizeof(int));
return b;
}
void delete_board(Board *b){
free(b->boardSpaces);
}
int main(void){
struct Board b = createBoard(2,3);
do_stuff_with(&b);
delete_board(&b);
}
/* 我没有通过编译器 运行 这个,所以请原谅打字错误 */
我可以在 C 中执行此操作吗?
我的代码出现错误
ERROR
minesweeper.c:19:19: error: expected ‘:’, ‘,’, ‘;’, ‘}’ or ‘__attribute__’ before ‘=’ token
int *boardSpaces = (int *)malloc(newBoard.rows * newBoard.columns * sizeof(int));
typedef struct boards
{
int rows, columns;
int *boardSpaces = malloc(rows * columns * sizeof(int));
} Board;
但是当我把它放在我的 main 中时它工作得很好。
我可以在结构中声明它吗,还是我遗漏了什么?
你不能运行像那样对结构中的变量起作用。
简短的回答是因为 rows
和 columns
在编译时没有任何价值。
你可以这样做,在这个函数中,create_board和delete_board本质上是模仿c++的构造函数和析构函数,但你必须手动调用它们。
struct Board
{
int rows, columns;
int *boardSpaces; // memory will be allocated when we need it
};
/* create a board with a given size, as memory is dynamically allocated, it must be freed when we are done */
struct Board createBoard(int rows, int columns){
struct Board b;
b.rows = rows;
b.columns = columns;
b.boardSpaces = malloc(rows * columns * sizeof(int));
return b;
}
void delete_board(Board *b){
free(b->boardSpaces);
}
int main(void){
struct Board b = createBoard(2,3);
do_stuff_with(&b);
delete_board(&b);
}
/* 我没有通过编译器 运行 这个,所以请原谅打字错误 */