Home > database >  Can I create a dynamic 2D array in C like this?
Can I create a dynamic 2D array in C like this?

Time:07-12

Can I use

size_t m, n;
scanf ("%zu%zu", &m, &n);
int (*a)[n] = (int (*)[n])calloc (m * n, sizeof (int));

to create a dynamic 2D array in C, whose size of rows and columns can be modified by function realloc during runtime?

CodePudding user response:

Also you can use pointer-to-pointer-to-int and alloc first array for "pointers to lines" and then init all items by allocating memory for "arrays of int".

Example:

#include <stdio.h>
#include <stdlib.h>

int main() {
    size_t m, n;
    scanf("%zu%zu", &m, &n);
    int **a = (int **)calloc(m, sizeof(int*));
    size_t i, j;
    for (i = 0; i < m; i  ) {
        a[i] = (int *)calloc(n, sizeof(int));
    }
    /// Work with array
    for (i = 0; i < m; i  ) {
        for (j = 0; j < n; j  ) {
            a[i][j] = i j;
            printf("%d ", a[i][j]);
        }
        printf("\n");
    }
    return 0;
}

Such approach allows to make realloc later

CodePudding user response:

This record

int (*a)[n] = (int (*)[n])calloc (m * n, sizeof (int));

is correct provided that the compiler supports variable length arrays.

It may be written also like

int (*a)[n] = calloc ( 1, sizeof ( int[m][n] ) );

On the other hand, there is a problem when you will use realloc and the number of columns must be changed. This can result in losing elements in the array in its last row because C memory management functions know nothing about types of objects for which the memory is allocated. They just allocate extents of memory of required sizes.

Otherwise if the compiler does not support variable length arrays you will need to allocate array of pointers and for each pointer an array of integers. This approach is more flexible in sense that you can reallocate separately columns and rows.

  • Related