要實現二維數組的行列互換,可以通過兩層循環來完成。具體步驟如下:
下面是一個示例代碼:
#include <stdio.h>
#define ROWS 3
#define COLS 4
void transpose(int arr[][COLS], int transposed[][ROWS]) {
for (int i = 0; i < ROWS; i++) {
for (int j = 0; j < COLS; j++) {
transposed[j][i] = arr[i][j];
}
}
}
int main() {
int arr[ROWS][COLS] = {{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}};
int transposed[COLS][ROWS];
transpose(arr, transposed);
printf("Original array:\n");
for (int i = 0; i < ROWS; i++) {
for (int j = 0; j < COLS; j++) {
printf("%d ", arr[i][j]);
}
printf("\n");
}
printf("\nTransposed array:\n");
for (int i = 0; i < COLS; i++) {
for (int j = 0; j < ROWS; j++) {
printf("%d ", transposed[i][j]);
}
printf("\n");
}
return 0;
}
運行該代碼,輸出結果為:
Original array:
1 2 3 4
5 6 7 8
9 10 11 12
Transposed array:
1 5 9
2 6 10
3 7 11
4 8 12
可以看到,原始數組的行列互換后,得到的新數組的行數等于原始數組的列數,新數組的列數等于原始數組的行數。