重新分配一个结构体,c
我有下一个结构
struct Board
{
int width;
int height;
char **board;
}
,我想扩展 **board,这意味着我需要更多内存,因此需要调用 重新分配()。所以我的问题是我该怎么做 - 我应该在数组中的每一行分别调用 realloc() 并在整个结构上调用它吗? 谢谢!
I have the next struct
struct Board
{
int width;
int height;
char **board;
}
And I would like to expand the **board, meaning I need more memory and thus the call to
realloc(). So my question is how do I do that - should I call realloc() on every line in the array separatly and the call it on the entire struct?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
对
board
调用realloc
将元素数量加1,然后对board[height]
调用malloc
(假设高度是第一个维度)添加新行Call
realloc
forboard
to increase the number of elements by 1, and then callmalloc
onboard[height]
(assuming height is the first dimension) to add a new row您需要在
board
上调用malloc
而不是realloc
。当实例化 Board 对象时,不会为成员 board 分配内存;所以这不是重新分配内存的问题,而是以多维数组。一旦您分配了内存,然后如果您需要扩展
board
(例如board
最初是2x2,现在您希望它是6x6),请调用realloc
的顺序与调用malloc
初始化board
的顺序相同。You need to call
malloc
notrealloc
onboard
. When you instantiate an object ofBoard
, no memory is allocated to the memberboard
; so it's not a question of reallocating memory, but allocating memory toboard
in the usual way for multidimensional arrays.Once, you've allocated memory, and then if you need to expand
board
(e.g.board
was initially 2x2 and now you want it to be 6x6), callrealloc
in the same order you calledmalloc
to initializeboard
.如果你想要更多的行,你应该在
board
上调用realloc
,如果你想扩展行,你需要在你的每一行上调用realloc
先前分配的(例如board[0]
、board[1]
等)If you want more lines, you should call
realloc
onboard
, if you want to expand lines, you need to callrealloc
on each line you previously allocated (e.g.board[0]
,board[1]
etc)如果您可以预测需要多少内存,那么最好只调用一次。否则可能会大大减慢整个过程。
If you can predict how much memory you need, it would be the best to only call it once. Doing otherwise might slow down the whole suff massively.