04-20-2006 11:03 AM
04-20-2006 12:01 PM
The key thing with functions which expect a 2D array is that the expect the memory to be contiguous. The 'best' way to achieve this is as follows:
#define NUM_ROWS 5
#define NUM_COLS 7
static int **array;
int SetupFunc(void)
{
int i, j;
// allocate the row pointers as usual
array = malloc(NUM_ROWS * sizeof(int *));
// allocate the rows as a continuous block of memory
*array = malloc(NUM_ROWS * NUM_COLS * sizeof(int));
// point the other row pointers to their 'row' within the block
for (i = 1; i < NUM_ROWS; ++i)
array[i] = *array + (NUM_COLS * i);
// fill like usual
for (i = 0; i < NUM_ROWS; ++i)
for (j = 0; j < NUM_COLS; ++j)
array[i][j] = i + j;
}
void CleanUp(void)
{
// free the big block of memory
free(*array);
// free the row pointers
free(array);
}
This is better for a variety of reasons. It decreases memory fragmentation, it requires fewer allocations and deallocations, it improves locality when portions of the heap are cached, it allows natural usage as a 2-D array, etc.
It also works with C functions which expect 2-D arrays. The only (small) caveat is that when you pass the array to an API function, you pass (*array) instead of (array).
Ex:
PlotIntensity(panel, PANEL_GRAPH, *array, NUM_COLS, NUM_ROWS, VAL_INTEGER, colorMapArray, 0, 2, 1, 1);
This passes the pointer to the large contiguous block you allocated, and works as expected.
Hope this helps,
-alex