Normally, when I create a dynamic 2D array I will first malloc the row pointers, then loop through rows and malloc each of rows. So, for example:
array = malloc( row_count * sizeof( int* ) );
for( int x = 0; x < row_count; x++ ){
array[x] = malloc( column_count * sizeof( int ) );
}
Once this is done I can use a syntax like:
data[3][5] = 52;
to set or get the values. The problem with this is that many mallocs are done which is both cpu-intensive and results in many fragments of memory, all of which have to be deallocated individually. The alternative is to allocate the array as a single block of memory. However, if I do this, I can no longer use the [ ][ ] syntax to refer to elements in the array and instead I have to do something like this:
data[ row_index * column_size + column_index ] = 52;
manually calculating the correct offset into the contiguous block. Is there a way to allocate a single block of memory for an array, yet still use the [ ][ ] syntax?