LabWindows/CVI

cancel
Showing results for 
Search instead for 
Did you mean: 

can I use a pointer to a two dimensional array in the PlotIntensity function?

When I use an integer array defined as:
 
int  **array;
 
and then allocate it and use it as the Z-array field in PlotIntensity Function, it does not plot the data in the correct order.  How do I go about using the PlotIntensity function with a double pointer array as the Z-array input? 
 
Thanks,
CTR
 
0 Kudos
Message 1 of 2
(3,138 Views)

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

0 Kudos
Message 2 of 2
(3,133 Views)