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

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

问题描述

我/ IKE知道,如何通过使用函数参数指针动态分配数组。这个功能应该是分配阵列10×10(支票跳过简单起见)。这可能吗?我究竟做错了什么?先谢谢了。

  INT array_allocate2DArray(INT **阵列,无符号整型size_x,无符号整型size_y)
{
    阵列=的malloc(size_x * sizeof的为(int *));    的for(int i = 0; I< size_x;我++)
        数组[我] =的malloc(size_y *的sizeof(INT));    返回0;
}诠释的main()
{
    INT **阵列;
    array_allocate2DArray(*放大器;阵列,10,10);
}


解决方案

尝试是这样的:

  INT array_allocate2DArray(INT *** P,无符号整型size_x,无符号整型size_y)
{
    INT **阵列=的malloc(size_x * sizeof的为(int *));    的for(int i = 0; I< size_x;我++)
        数组[我] =的malloc(size_y *的sizeof(INT));    * P =阵列;
    返回0;
}
INT **阵列;
array_allocate2DArray(安培;阵列,10,10);

我用的是临时 P 以避免混淆。

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);
}

解决方案

Try something like this:

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);

I used the temporary p to avoid confusion.

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

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