Search code examples
cmultidimensional-arraydynamic-allocation

Allocating 2D array with pointer to fixed-size array


Is it valid in C to dynamically allocate 2d arrays this way?

//fixed size
int (*arr2d)[9][9]=malloc(sizeof(int[9][9]));

//variable size
int x=5,y=3;
int (*arr2d)[x][y]=malloc(sizeof(int[x][y]));

//assignment
(*arr2d)[0][1]=2;

EDIT: By "valid" I mean, are there any pitfalls as opposed to:

int i,x=5,y=10;
int **arr2d=malloc(sizeof(int*[x]));
for(i=0;i < x;i++)
    arr2d[i]=malloc(sizeof(int[y]));

arr2d[0][0]=5;

Solution

  • The only real issue is if you request more memory than the malloc call can satisfy (you may have enough memory available, but not in a single, contiguous block).

    To save your sanity, do something like this instead:

    T (*arr)[cols] = malloc( sizeof *arr * rows );
    

    This will allow you to index it as arr[i][j] instead of (*arr)[i][j].