Function to left shift a 2D array in C

后端 未结 3 1429
天命终不由人
天命终不由人 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: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);
    

提交回复
热议问题