【发布时间】:2013-05-25 05:50:04
【问题描述】:
我需要定义分配二维数组的函数,但它应该只调用一次malloc。
我知道怎么分配它(-std=c99):
int (*p)[cols] = malloc (sizeof(*p) * rows);
但我不知道如何从函数中返回它。 Return 不是选项,因为一旦函数结束(或至少部分结束),数组将停止存在。因此,将数组传递给此函数的唯一选项是作为参数,但上述解决方案需要在声明中定义列数。有没有可能?
谢谢。
感谢用户 kotlomoy,我设法解决了这个问题:
...
#define COLS 10
#define ROWS 5
int (*Alloc2D())[COLS]
{
int (*p)[COLS] = malloc(sizeof(*p) * ROWS);
return p;
}
//and this is example how to use it, its not elegant,
//but i was just learning what is possible with C
int main(int argc, char **argv)
{
int (*p)[COLS] = Alloc2D();
for (int i = 0; i < ROWS; i++)
for(int j = 0; j < COLS; j++)
p[i][j] = j;
for (int i = 0; i < ROWS; i++){
for(int j = 0; j < COLS; j++)
printf("%d", p[i][j]);
printf("\n");
}
return 0;
}
【问题讨论】:
-
你真的应该添加
c99标签
标签: arrays function return malloc 2d