要实现二维数组的行列互换,可以通过两层循环来完成。具体步骤如下:
下面是一个示例代码:
#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
可以看到,原始数组的行列互换后,得到的新数组的行数等于原始数组的列数,新数组的列数等于原始数组的行数。