Home > Mobile >  Reverse order of rows in 2d array
Reverse order of rows in 2d array

Time:10-12

I'm trying to figure out how to "flip" an 2d array like this:

{{1, 2, 3},
 {4, 5, 6},
 {7, 8, 9}}
{{7, 8, 9},
 {4, 5, 6},
 {1, 2, 3}}

Searching how to reverse/flip rows of 2D array just returns how to reverse the content of the rows, or some other variation that doesn't work like I need

CodePudding user response:

Swapping rows work exactly the same way as swapping integers, only instead of assigning you need to copy the memory.

void reverseRows(size_t rows, size_t cols, int (*array)[cols])
{
    int temp[cols];
    size_t last = rows - 1, first = 0;

    while(last > first)
    {
        memcpy(temp, array[first], sizeof(*array));
        memcpy(array[first  ], array[last], sizeof(*array));
        memcpy(array[last--], temp, sizeof(*array));
    }
}

#define N 3

int main(void)
{
    int a[N][N] = 
    {
        { 1, 2, 3 },
        { 4, 5, 6 },
        { 7, 8, 9 }
    };

    for ( size_t i = 0; i < N; i   )
    {
        for ( size_t j = 0; j < N; j   )
        {
            printf( "%d ", a[i][j] );
        }

        putchar( '\n' );
    }

    putchar( '\n' );

    reverseRows(N,N,a);

    for ( size_t i = 0; i < N; i   )
    {
        for ( size_t j = 0; j < N; j   )
        {
            printf( "%d ", a[i][j] );
        }

        putchar( '\n' );
    }
}

https://godbolt.org/z/qxW3rG3sx

CodePudding user response:

Here you are.

#include <stdio.h>

void swap_arrays( int *a1, int *a2, size_t n )
{
    for ( size_t i = 0; i < n; i   )
    {
        int tmp = a1[i];
        a1[i] = a2[i];
        a2[i] = tmp;
    }
}

int main(void) 
{
    enum { N = 3 };

    int a[N][N] = 
    {
        { 1, 2, 3 },
        { 4, 5, 6 },
        { 7, 8, 9 }
    };

    for ( size_t i = 0; i < N; i   )
    {
        for ( size_t j = 0; j < N; j   )
        {
            printf( "%d ", a[i][j] );
        }

        putchar( '\n' );
    }

    putchar( '\n' ); 

    for ( size_t i = 0; i < N / 2; i   )
    {
        swap_arrays( a[i], a[N - i - 1], N );
    }

    for ( size_t i = 0; i < N; i   )
    {
        for ( size_t j = 0; j < N; j   )
        {
            printf( "%d ", a[i][j] );
        }

        putchar( '\n' );
    }

    putchar( '\n' ); 

    return 0;
}

The program output is

1 2 3 
4 5 6 
7 8 9 

7 8 9 
4 5 6 
1 2 3 
  • Related