如何在c程序中上移二维数组列



我需要在2D数组中上移列,并将最后一行设置为零。

如果我调用shift up一次,则需要将每列的值向上移动,并将最后一列设置为零。输入阵列输出阵列

1 2 3         4 5 6 
4 5 6  ==>    7 8 9
7 8 9         1 1 1
1 1 1         0 0 0

最后一行在调用shift UP之后变为第一行。

void shiftup()
{
for(int col=0;col<=3;col++)
{
int start = 0;
int end = 3 - 1;
while (start < end) {
swap(&arr[start][col], &arr[end][col]);
start++;
end--;
}
}
void swap(int* a, int* b)
{
int temp = *a;
*a = *b;
*b = temp;
}

有人能建议修改上面的代码吗。

应用标准函数memmovememset更简单,例如

memmove( a, a + 1, sizeof( a ) - sizeof( a[0] ) );
memset( a + 3, 0, sizeof( *a ) );

这是一个演示程序

#include <stdio.h>
#include <string.h >
int main( void )
{
enum { M = 4, N = 3 };
int a[M][N] =
{
{ 1, 2, 3 },
{ 4, 5, 6 },
{ 7, 8, 9 },
{ 1, 1, 1 }
};
memmove( a, a + 1, sizeof( a ) - sizeof( a[0] ) );
memset( a + M - 1, 0, sizeof( *a ) );
for (size_t i = 0; i < M; i++)
{
for (size_t j = 0; j < N; j++)
{
printf( "%d ", a[i][j] );
}
putchar( 'n' );
}
}

程序输出为

4 5 6
7 8 9
1 1 1
0 0 0

至于你的代码,那么至少这是循环

for(int col=0;col<=3;col++)
^^^^^^

不正确。你必须写

for(int col = 0;col < 3;col++)

这些调用的函数交换

swap(&arr[start][col], &arr[end][col]);

没有道理。

相关内容

最新更新