Using a pointer to a dynamic 2D Array within a struct

夙愿已清 提交于 2019-12-04 20:19:11

You either need to return the array_info structure (as amended) from the function or (more usually) pass a pointer to the array_info structure into the function so that the changes you make affect the value in the calling function.

typedef struct
{
    int    height;
    int    width;
    int    bottom;
    unsigned int **dat_ptr;  // Double pointer, not triple pointer
} array_info;

void create_array(array_info *A)
{
    unsigned int **array = malloc(sizeof(*array) * A->height);
    for (int i = 0; i < A->height; ++i)
        array[i] = malloc(sizeof(**array) * A->width);
    A->dat_ptr = array;
}

I assume you do some checking on the memory allocations somewhere; the logical place is this function, though. Recovery from a failure part way through is fiddly (but necessary if you are going to return from the function rather than exit from the program).

void create_array(array_info *A)
{
    unsigned int **array = malloc(sizeof(*array) * A->height);
    if (array != 0)
    {
        for (int i = 0; i < A->height; ++i)
        {
             if ((array[i] = malloc(sizeof(**array) * A->width)) == 0)
             {
                 for (int j = 0; j < i; j++)
                      free(array[j]);
                 free(array);
                 array = 0;
                 break;
             }
        }
    }
    A->dat_ptr = array;
}

The calling function knows that the function failed if the dat_ptr member is null on return from create_array(). It might be better to provide a success/failure return value.

I'm using C99, so the calling code might be:

array_info array = { .height = 10, .width = 20, .dat_ptr = 0 };
create_array(&array);
if (array->dat_ptr == 0)
    ...error handling...

Note that the code in create_array() might need to check for a null pointer, for negative or zero width or height. I'm not clear what the bottom element should contain, so I left it uninitialized, which gives me half an excuse for using designated initializers. You can also write the initializer quite clearly without using designated initializers.

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