更改固定二维数组以采用运行时给定的大小
我一整天都在努力解决这个问题...
到目前为止,我的代码按计划工作,想法是我必须更改 tCell * cells[3][5]
;获取运行时给定的大小。我需要进行哪些更改才能保留功能?
typedef struct {
int active;
} tCell;
typedef struct {
tCell * cells[3][5];
} tGrid;
// creates a grid and initialize all the cells to NULL
tGrid *init_grid()
{
tGrid *grid= malloc(sizeof(tGrid));
if(grid == NULL)
exit(127); // failed to malloc
int i, j;
for(i=0; i < 3; i++)
for(j=0; j < 5; j++)
grid->cells[i][j]= NULL;
return grid;
}
// adds a cell to the grid
void add_cell(tGrid *grid)
{
tCell cell;
int y = rand() % 4;
if(grid->cells[0][y] != NULL)
exit(127); // cell is taken
cell.active = 1;
grid->cells[0][y] = &cell;
}
void remove_cell(tGrid *grid, int x, int y)
{
if(x < 0 || x > 3 || y < 0 || y > 5)
exit(127); // out of bounds
grid->cells[x][y]= NULL;
}
基本上,init_grid
必须将 x
和 y
作为参数:
tGrid *init_grid(int x, int y);
但是,如何更改 tGrid 结构定义呢?到目前为止,无论我尝试过什么,都会产生编译器错误(例如 tCell * cells[][];
)
在稍微相关的注释中,您如何阅读“tCell * cells[3][ 5];
”大声?
注意:
- 这是一个C问题
- 我正在使用gcc 4.1来编译代码
I've been trying to wrap my head around this the whole day...
The code that I have so far works as planed, the idea is that I'll have to change tCell * cells[3][5]
; to take a size that's given at runtime. What changes do I need to make to retain the functionality?
typedef struct {
int active;
} tCell;
typedef struct {
tCell * cells[3][5];
} tGrid;
// creates a grid and initialize all the cells to NULL
tGrid *init_grid()
{
tGrid *grid= malloc(sizeof(tGrid));
if(grid == NULL)
exit(127); // failed to malloc
int i, j;
for(i=0; i < 3; i++)
for(j=0; j < 5; j++)
grid->cells[i][j]= NULL;
return grid;
}
// adds a cell to the grid
void add_cell(tGrid *grid)
{
tCell cell;
int y = rand() % 4;
if(grid->cells[0][y] != NULL)
exit(127); // cell is taken
cell.active = 1;
grid->cells[0][y] = &cell;
}
void remove_cell(tGrid *grid, int x, int y)
{
if(x < 0 || x > 3 || y < 0 || y > 5)
exit(127); // out of bounds
grid->cells[x][y]= NULL;
}
Basically, init_grid
will have to take x
and y
as parameters:
tGrid *init_grid(int x, int y);
But then, how do I change tGrid struct definition? Whatever I've tried so far yielded a compiler error (e.g. tCell * cells[][];
)
On a slightly related note, how do you read "tCell * cells[3][5];
" outloud?
Note:
- this is a C question
- I'm using gcc 4.1 to compile the code
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
简单的。
并分配:
完成。
或者,您也可以使用 do:
来代替
do-while
循环。不同之处在于,在第一种情况下,每一行将是内存中的一个单独的数组,这在处理该事物时可能很有用。当然,最终,对于每个
malloc
都必须有一个free
。Easy.
And allocating:
Done.
Or, you can also do:
instead of the
do-while
loop. The difference is that in the first case, each row will be a separate array in the memory, which may be useful when handling the thing.Of course, in the end, for each
malloc
there has to be afree
.