Dynamic allocation of 2D array within function (using pointers to return adress of allocated object)

岁酱吖の 提交于 2019-11-29 12:58:57

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.

I came across this post when I was facing a similar problem (I was looking for a way to dynamically allocate an array of strings in C). I prefer to return the array pointer from the function. The following worked for me (I adapted it for your array of integers). I arbitrarily set 99 for each value so I could see them printed out in main.

int **array_allocate2DArray(unsigned int size_x, unsigned int size_y)
{
        int i;
        int **arr;

        arr = malloc(size_x*(sizeof(int*)));

        for (i=0 ; i<size_x ; i++){
                arr[i] = malloc(size_y);
                *arr[i] = 99;
        }

        return arr;

}

int main(void)
{
        int i;
        int **arr;

        arr = array_allocate2DArray(10, 10);

        for (i=0 ; i<10 ; i++){
                printf("%d\n", *arr[i]);
                free(arr[i]);
        }
        free(arr);

        return 0;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!