如何在C程序中向上移动二维数组列

How to shift 2d array column up in c program

我需要将二维数组中的列向上移动并将最后一行设置为零。

如果我调用 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 循环

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

不正确。你必须改写

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

以及函数交换的这些调用

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

没有意义。