Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dynamically allocate a contiguous block of memory for a 2D array

Tags:

If I allocate a 2D array like this int a[N][N]; it will allocate a contiguous block of memory.

But if I try to do it dynamically like this :

int **a = malloc(rows * sizeof(int*));
for(int i = 0; i < rows; i++) 
   a[i] = malloc(cols * sizeof(int));

This maintains a unit stride between the elements in the rows, but this may not be the case between rows.

One solution is to convert from 2D to 1D, besides that, is there another way to do it?

like image 705
dreamcrash Avatar asked Nov 23 '12 19:11

dreamcrash


People also ask

Can we allocate a 2 dimensional array dynamically?

A 2D array can be dynamically allocated in C using a single pointer. This means that a memory block of size row*column*dataTypeSize is allocated using malloc and pointer arithmetic can be used to access the matrix elements.

Is 2D array contiguous?

As a result, the element locations within a row are contiguous, but elements are not contiguous across rows of the 2D array.


1 Answers

If your array dimensions are known at compile time:

#define ROWS ...
#define COLS ...

int (*arr)[COLS] = malloc(sizeof *arr * ROWS);
if (arr) 
{
  // do stuff with arr[i][j]
  free(arr);
}

If your array dimensions are not known at compile time, and you are using a C99 compiler or a C2011 compiler that supports variable length arrays:

size_t rows, cols;
// assign rows and cols
int (*arr)[cols] = malloc(sizeof *arr * rows);
if (arr)
{
  // do stuff with arr[i][j]
  free(arr);
}

If your array dimensions are not known at compile time, and you are not using a C99 compiler or a C2011 compiler that supports variable-length arrays:

size_t rows, cols;
// assign rows and cols
int *arr = malloc(sizeof *arr * rows * cols);
{
  // do stuff with arr[i * rows + j]
  free(arr);
}
like image 107
John Bode Avatar answered Oct 16 '22 10:10

John Bode