Function to left shift a 2D array in C

后端 未结 3 1430
天命终不由人
天命终不由人 2021-01-28 17:43

I\'m writing a function within my program to left shift all the numbers in an array that was passed to the function. An example is:

1 2 3 
4 5 6
<
相关标签:
3条回答
  • 2021-01-28 18:08
    array[r][c] = array[r][c-1];
    

    should be

    array[r][c-1] = array[r][c];
    

    Likewise for the row shift.

    0 讨论(0)
  • 2021-01-28 18:09

    2-D arrays are contiguous in memory, so you can iterate over it as if it were a 1-D array:

    void left_rotate(int array[][N])
    {
        int *flat = (int *)array;
        int temp = flat[0];
    
        for ( size_t i = 1; i < M*N; ++i )
            flat[i-1] = flat[i];
    
        flat[M*N-1] = temp;
    
    }
    

    The for loop could also be replaced with a single block move:

    memmove(&flat[0], &flat[1], (M*N-1) * sizeof *flat);
    
    0 讨论(0)
  • 2021-01-28 18:18

    You can go throw the array, having a pointer following the last place you visited, and moving the elements, as in this example:

    #define nrows 4
    #define ncols 4
    
    int array[nrows][ncols] = {
        { 1, 2, 3, 4, },
        { 5, 6, 7, 8, },
        { 9, 10, 11, 12, },
        { 13, 14, 15, 16, },
    };
    
    int main()
    {
        int row, col;
        int saved_int;
        int *p = &saved_int;
    
        /* rotate elements */
        for(row = 0; row < nrows; row++)
            for (col = 0; col < ncols; col++) {
                *p = array[row][col];
                p = &array[row][col];
            } /* for */
        *p = saved_int;
    
        /* print matrix */
        for (row = 0; row < nrows; row++) {
            for (col = 0; col < ncols; col++)
                printf( "%s%d",
                        (col ? "\t" : ""),
                        array[row][col]);
            printf("\n");
        } /* for */
        return 0;
    } /* main */
    
    0 讨论(0)
提交回复
热议问题