【发布时间】:2012-02-03 03:23:22
【问题描述】:
我在一次采访中被问到如何分配一个二维数组,下面是我的解决方案。
#include <stdlib.h>
int **array;
array = malloc(nrows * sizeof(int *));
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
}
}
我以为我做得很好,但后来他让我用一个 malloc() 声明而不是两个来做这件事。我不知道如何实现它。
谁能建议我在单个malloc() 中做到这一点?
【问题讨论】:
-
实际上这是在进行 (nrows + 1) 次 malloc 调用。
-
警告:这里发布的许多答案都是有害的。阅读 John Bode 和 chux 的答案,忽略其余部分。
标签: c