编写一个函数,实现对一个二维数组的行列互换,使用指针作为函数参数附带源代码
时间: 2024-03-11 13:50:54 浏览: 65
好的,下面是实现对一个二维数组的行列互换的函数,并附带源代码:
```c
#include <stdio.h>
void transpose(int *arr, int m, int n) {
int temp[n][m];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
temp[j][i] = *(arr + i * n + j);
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
printf("%d ", temp[i][j]);
}
printf("\n");
}
}
int main() {
int arr[3][4] = {{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}};
int m = 3;
int n = 4;
printf("Original Array:\n");
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
printf("%d ", arr[i][j]);
}
printf("\n");
}
printf("\nTransposed Array:\n");
transpose(&arr[0][0], m, n);
return 0;
}
```
这里使用了一个临时数组temp来保存转置后的结果,首先通过两个for循环将原数组的元素复制到temp数组中,然后再通过两个for循环输出转置后的结果。
在主函数中,我们定义了一个3行4列的二维数组arr,然后将其传递给transpose函数进行转置操作,并输出转置前和转置后的结果。
希望这个例子能够帮助您更好地理解指针和二维数组的操作。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20210720083327.png)
![-](https://img-home.csdnimg.cn/images/20210720083327.png)
![-](https://img-home.csdnimg.cn/images/20210720083327.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![application/msword](https://img-home.csdnimg.cn/images/20210720083327.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![application/pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://img-home.csdnimg.cn/images/20210720083327.png)
![-](https://img-home.csdnimg.cn/images/20210720083327.png)
![-](https://img-home.csdnimg.cn/images/20210720083327.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://img-home.csdnimg.cn/images/20210720083327.png)
![-](https://img-home.csdnimg.cn/images/20210720083327.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)