在结构中声明2D数组而不知道结构中的大小?

时间:2015-04-18 22:06:57

标签: c arrays struct malloc

我可以在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;

但是当我把它放在我的主要部分时,效果很好。

我可以在结构中声明这个,还是只是我遗漏了什么?

1 个答案:

答案 0 :(得分:2)

你不能像这样对结构中的变量运行函数。

简短回答是因为rowscolumns在编译时没有任何价值。

你可以这样做,在这个函数中,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);

}

/ *我没有通过编译器运行它,所以原谅错别字* /