dynamic allocating array of arrays in C

2020-01-27 03:20发布

I don't truly understand some basic things in C like dynamically allocating array of arrays. I know you can do:

int **m;

in order to declare a 2 dimensional array (which subsequently would be allocated using some *alloc function). Also it can be "easily" accessed by doing *(*(m + line) + column). But how should I assign a value to an element from that array? Using gcc the following statement m[line][column] = 12; fails with a segmentation fault.

Any article/docs will be appreciated. :-)

7条回答
放荡不羁爱自由
2楼-- · 2020-01-27 04:11

Although I agree with the other answers, it is in most cases better to allocate the whole array at once, because malloc is pretty slow.


int **
array_new(size_t rows, size_t cols)
{
    int **array2d, **end, **cur;
    int *array;

    cur = array2d = malloc(rows * sizeof(int *));
    if (!array2d)
        return NULL;

    array = malloc(rows * cols * sizeof(int));
    if (!array)
    {
        free(array2d);
        return NULL;
    }

    end = array2d + rows;
    while (cur != end)
    {
        *cur = array;
        array += cols;
        cur++;
    }

    return array2d;
}

To free the array simply do: free(*array); free(array);

Note: this solution only works if you don't want to change the order of the rows, because you could then lose the address of the first element, which you need to free the array later.

查看更多
登录 后发表回答