C程序中怎么把一个二维数组行列互换
时间: 2023-12-07 20:45:46 浏览: 85
可以通过循环遍历二维数组,将每一行与相应的列进行交换来实现行列互换。具体的实现方式如下:
```c
#include <stdio.h>
#define ROW 3
#define COL 4
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
void transpose(int arr[ROW][COL]) {
for (int i = 0; i < ROW; i++) {
for (int j = i + 1; j < COL; j++) {
swap(&arr[i][j], &arr[j][i]);
}
}
}
int main() {
int arr[ROW][COL] = {{1,2,3,4}, {5,6,7,8}, {9,10,11,12}};
printf("Before transpose:\n");
for (int i = 0; i < ROW; i++) {
for (int j = 0; j < COL; j++) {
printf("%d ", arr[i][j]);
}
printf("\n");
}
transpose(arr);
printf("After transpose:\n");
for (int i = 0; i < COL; i++) {
for (int j = 0; j < ROW; j++) {
printf("%d ", arr[i][j]);
}
printf("\n");
}
return 0;
}
```
运行结果如下:
```
Before transpose:
1 2 3 4
5 6 7 8
9 10 11 12
After transpose:
1 5 9
2 6 10
3 7 11
4 8 12
```
阅读全文