Function to left shift a 2D array in C

后端 未结 3 1431
天命终不由人
天命终不由人 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: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 */
    

提交回复
热议问题