设置2Darrays,稍后更改大小 – C.
是否可以在C中声明2D数组,然后稍后设置其大小? 我知道在C中你必须处理记忆等等,但是尽管我都在寻找,但我找不到这个问题的答案。
我目前的例子是……
int boardsize, linewin; char array[1][1]; //boardsize is set within here. array = [boardsize][boardsize];
使用C,您需要使用指针进行自己的动态数组管理。
请参阅以下文章,了解如何使用分配的内存区域执行此操作。
Malloc是C中的2D数组
使用malloc分配具有不同行长度的多维数组
由于您要修改这些,您可能还需要使用realloc()
函数或free()
函数来释放已分配的内存。
有关使用realloc()函数的信息,请查看以下堆栈溢出。
在C中重新分配双2D数组
二维动态数组(c中的realloc)
编辑 – 添加一个例子
以下是malloc()
二维数组和realloc()
二维数组的两个函数。 如果将NULL指针传递给realloc2dCArray()
以便重新分配内存区域,实际上可以使用realloc()
版本。
我试图做的是对所需的所有内存使用单个malloc()
和realloc()
,这样你就可以通过一次调用free()
来free()
内存。
char **malloc2dCArray (int nRows, int nCols) { // use a single malloc for the char pointers to the first char of each row // so we allocate space for the pointers and then space for the actual rows. char **pArray = malloc (sizeof(char *) * nRows + sizeof(char) * nCols * nRows); if (pArray) { // calculate offset to the beginning of the actual data space char *pOffset = (char *)(pArray + nRows); int i; // fix up the pointers to the individual rows for (i = 0; i < nRows; i++) { pArray[i] = pOffset; pOffset += nCols; } } return pArray; } char **realloc2dCArray (char **pOld, int nRows, int nCols) { // use a single realloc for the char pointers to the first char of each row // so we reallocate space for the pointers and then space for the actual rows. char **pArray = realloc (pOld, sizeof(char *) * nRows + sizeof(char) * nCols * nRows); if (pArray) { // calculate offset to the beginning of the actual data space char *pOffset = (char *)(pArray + nRows); int i; // fix up the pointers to the individual rows for (i = 0; i < nRows; i++) { pArray[i] = pOffset; pOffset += nCols; } } return pArray; }
要使用这些function,您可以执行以下操作:
char **pChars = malloc2dCArray (16, 8); int i, j; for (i = 0; i < 16; i++) { for (j = 0; j < 8; j++) { pChars[i][j] = 0; } }
要执行realloc()
您需要检查realloc()
有效,因此请使用临时变量并在使用之前检查NULL。
{ char **pChars2 = realloc2dCArray (pChars, 25, 8); if (pChars2) pChars = pChars2; }
如果提供NULL指针,也可以使用realloc()
版本,因为如果指向realloc()
的malloc()
的指针为NULL,则realloc()
将执行malloc()
。
我使用调试器对此进行了一些测试,看起来它对我有用。