[英]How to shift 2d array column up in c program
我需要在 2D 數組中將列向上移動並將最后一行設置為零。
如果我調用 shift up 一次需要將每列值向上移動並將最后一列設置為零。 輸入數組 output 數組
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;
}
任何人都可以建議更改上述代碼。
例如,應用標准函數memmove
和memset
更簡單
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' );
}
}
程序 output 是
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++)
和 function 交換的這些調用
swap(&arr[start][col], &arr[end][col]);
沒有意義。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.