用于在C中左移2Darrays的function

我正在我的程序中编写一个函数来左移所有传递给函数的数组中的数字。 一个例子是:

1 2 3 4 5 6 

 2 3 4 5 6 1 

我的代码是:

 void LeftShift(int array[][N])/*Get the array from main*/ { int r, c, temp; for(r = 0; r < M; r++) { //Start at row 0 and add one each time for(c = 0; c  0) { array[r][c] = array[r][c-1]; //Number is moved over one if its not the first column } else if(c == 0 && r > 0) { //If its first column but not first row array[r][c] = array[r-1][N-1];//Move number up one row and too last column } else { temp = array[r][c];//If its first column and first row store value in temp } } } array[M-1][N-1] = temp;//Put temp value at end of array } 

当我打印出来时,我得到的是数组中每个点的原始数组中的第一个数字。 M在顶部定义为6,N定义为5.运行后,我调用一个打印出新数组的函数,我得到的是数组中第一个值30次。

2-D数组在内存中是连续的,因此您可以像对待1-D数组一样迭代它:

 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; } 

for循环也可以用单个块移动替换:

 memmove(&flat[0], &flat[1], (M*N-1) * sizeof *flat); 
 array[r][c] = array[r][c-1]; 

应该

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

同样对于行移位。

您可以抛出数组,在您访问的最后一个位置后面有一个指针,并移动元素,如下例所示:

 #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 */