函数内二维数组的动态分配(使用指针返回分配对象的地址) [英] Dynamic allocation of 2D array within function (using pointers to return adress of allocated object)

查看:35
本文介绍了函数内二维数组的动态分配(使用指针返回分配对象的地址)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想/ike 知道,如何使用函数参数将指针传递给动态分配的数组.这个函数应该分配数组 10x10(为了简单起见,跳过了检查).这可能吗?我究竟做错了什么?提前致谢.

I'd /ike to know, how to pass pointers to dynamically allocated arrays using function arguments. This function is supposed to allocate array 10x10 (checks skipped for simplicity sake). Is this possible? What am i doing wrong? Thanks in advance.

int array_allocate2DArray ( int **array, unsigned int size_x, unsigned int size_y)
{
    array = malloc (size_x * sizeof(int *));

    for (int i = 0; i < size_x; i++)
        array[i] = malloc(size_y * sizeof(int));

    return 0;
}

int main()
{
    int **array;
    array_allocate2DArray (*&array, 10, 10);
}

推荐答案

试试这个:

int array_allocate2DArray (int ***p, unsigned int size_x, unsigned int size_y)
{
    int **array = malloc (size_x * sizeof (int *));

    for (int i = 0; i < size_x; i++)
        array[i] = malloc(size_y * sizeof(int));

    *p = array;
    return 0;
}


int **array;
array_allocate2DArray (&array, 10, 10);

为了避免混淆,我使用了临时的 p.

I used the temporary p to avoid confusion.

这篇关于函数内二维数组的动态分配(使用指针返回分配对象的地址)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆