功能左移在C二维数组 [英] Function to left shift a 2D array in C
问题描述
我在我的计划,留在传递给函数的数组转移所有的数字中写一个函数。一个例子是:
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
变为
2 3 4
5 6 1
我的code是:
My code is:
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 < N; c++) { //Start at column 0 and add one each time
if(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倍,在数组中。
When I print this out all I get is the first number from the original array in every spot in the array. M is defined at the top to be 6 and N is defined to be 5. After this runs, I call a function that prints out the new array and all I get is the first value 30 times in an array.
推荐答案
2-D数组是在内存中连续的,所以你可以迭代它,好像它是一维数组:
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);
这篇关于功能左移在C二维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!