我有下一个结构
struct Board
{
int width;
int height;
char **board;
}
我想扩展 **board,这意味着我需要更多内存,因此需要调用 realloc()。所以我的问题是我该怎么做 - 我应该在数组中的每一行分别调用 realloc() 并在整个结构上调用它吗?谢谢!
调用realloc
将board
元素个数加1,然后调用malloc
(board[height]
假设高度为第一维)添加新行
如果你想要更多行,你应该调用realloc
on board
,如果你想扩展行,你需要调用realloc
你之前分配的每一行(例如board[0]
,board[1]
等)
如果您可以预测需要多少内存,最好只调用一次。否则可能会大大减慢整个过程。
你需要打电话malloc
not realloc
on board
。当您实例化 的对象时Board
,不会为该成员分配内存board
;所以这不是重新分配内存的问题,而是以board
通常的方式为多维数组分配内存。
#include <stdlib.h>
int **array;
array = malloc(nrows * sizeof(int *));
if(array == NULL)
{
fprintf(stderr, "out of memory\n");
exit or return
}
for(i = 0; i < nrows; i++)
{
array[i] = malloc(ncolumns * sizeof(int));
if(array[i] == NULL)
{
fprintf(stderr, "out of memory\n");
exit or return
}
}
曾经,您已经分配了内存,然后如果您需要扩展board
(例如board
,最初是 2x2,现在您希望它是 6x6),请realloc
按照您调用的相同顺序调用malloc
initialize board
。