Phil
Phil

Reputation: 627

What is an efficient way to get column from multi-dimensional array in C?

I have two structs: ARRAY2D (multidimensional) and ARRAY (one-dimensional). I would like to get a column from type ARRAY2D and copy it into type ARRAY.

Although my code works below, and I recognize this is probably a poor way of getting a column from an array, I'm curious what optimizations there might be to avoid an O(n2) algorithm. What is an efficient way to get a column from an array in C?

BOOL arr2_getColumn(ARRAY2D *arr, const int column_index, ARRAY *returnedArray)
{
    int x, y;
    int i = 0;

    /* Check for valid array. */
    if (arr->blnIsInit != TRUE)
        return FALSE;

    /* Initialize array with the column's height. */ 
    if (!arr_init(returnedArray, arr->height))
        return FALSE;

    /* Copy over column. */
    for (y = 0; y < arr->height; y++)
    {
        for (x = 0; x <= column_index; x++)
        {
            if (x == column_index)
            { 
                returnedArray->array[i] = arr->array[y * arr->width + x];
                i++;
            } 
        }
    } 

    /* Set the new size. */
    returnedArray->size = arr->height;

    return TRUE;
}

Upvotes: 0

Views: 101

Answers (2)

JohnH
JohnH

Reputation: 2711

Get rid of i and x.

for (y = 0; y < arr->height; y++)
{
    returnedArray->array[y] = arr->array[y * arr->width + column_index];
} 

Upvotes: 2

user3569263
user3569263

Reputation: 15

/* Copy over column. */

for (y = 0; y < arr->height; y++)
{
    x = column_index;
    returnedArray->array[i] = arr->array[y * arr->width + x];
    i++;
} 

Upvotes: 0

Related Questions