我正在尝试实现类似于Conway的生活游戏的单元格网格。
虽然每个单独的网格在两个维度上都应具有固定的大小,但我希望有一个Grid结构可以在两个维度上都具有任意大小。
这类似于如何将数组设置为任意大小,但是一旦初始化后的数组将具有固定的大小。
这是我到目前为止的内容:
typedef struct Cell {
int data;
// stuff to be added later
} Cell;
typedef struct Grid {
unsigned width;
unsigned height;
Cell cell[][];
} Grid;
Grid initGrid(unsigned width, unsigned height) {
Grid g;
g.width = width;
g.height = height;
g.cell = malloc( sizeof(Cell)*width*height );
return g;
}
Run Code Online (Sandbox Code Playgroud)
但是我收到以下编译时错误:
main.c|12|note: declaration of `‘cell’ as multidimensional array must have bounds for all dimensions except the first|
Run Code Online (Sandbox Code Playgroud)
如何定义
Grid大小灵活的数据类型?
发布脚本:作为C新手,我认为以下方法会起作用:
typedef struct Grid {
unsigned width;
unsigned …Run Code Online (Sandbox Code Playgroud) c arrays struct multidimensional-array dynamic-memory-allocation