0

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;
}
Cœur
  • 37,241
  • 25
  • 195
  • 267
Phil
  • 607
  • 1
  • 8
  • 22
  • possible duplicate of [How to get column of a multidimensional array in C/C++?](http://stackoverflow.com/questions/15258084/how-to-get-column-of-a-multidimensional-array-in-c-c) – t1w Apr 24 '14 at 17:43
  • Also, we cannot know what ARRAY2d and ARRAY are supposed to be. – Gandaro Apr 24 '14 at 17:57

2 Answers2

2

Get rid of i and x.

for (y = 0; y < arr->height; y++)
{
    returnedArray->array[y] = arr->array[y * arr->width + column_index];
} 
JohnH
  • 2,713
  • 12
  • 21
0

/* Copy over column. */

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