将三乘三的矩阵转置用指针数组
时间: 2024-06-14 16:03:20 浏览: 17
以下是将三乘三的矩阵转置用指针数组的示例代码:
```c
#include <stdio.h>
int main() {
int a[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
int *p[3];
int i, j;
for (i = 0; i < 3; i++) {
p[i] = a[i];
}
for (i = 0; i < 3; i++) {
for (j = i; j < 3; j++) {
int temp = *(p[i] + j);
*(p[i] + j) = *(p[j] + i);
*(p[j] + i) = temp;
}
}
for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++) {
printf("%d ", a[i][j]);
}
putchar('\n');
}
return 0;
}
```
输出结果为:
```
1 4 7
2 5 8
3 6 9
```
相关问题
编辑函数将5乘5的矩阵转置 用指针
可以用下面的代码实现:
```c
void transpose(int (*matrix)[5]) {
int i, j;
for (i = 0; i < 5; i++) {
for (j = i + 1; j < 5; j++) {
int temp = matrix[i][j];
matrix[i][j] = matrix[j][i];
matrix[j][i] = temp;
}
}
}
```
其中,`matrix`是一个指向整型数组的指针,指向一个5行5列的矩阵。函数中的两个循环依次遍历矩阵中的每个元素,将其与其对称位置的元素交换。这样就实现了矩阵的转置。
矩阵转置(指针专题)
当我们使用指针来进行矩阵转置时,可以通过操作指针来交换矩阵的元素位置。下面是一个示例代码,演示了如何使用指针来实现矩阵转置:
```c
#include <stdio.h>
void transposeMatrix(int *matrix, int rows, int cols) {
for (int i = 0; i < rows; i++) {
for (int j = i + 1; j < cols; j++) {
// 交换 matrix[i][j] 和 matrix[j][i] 的值
int temp = *(matrix + i * cols + j);
*(matrix + i * cols + j) = *(matrix + j * cols + i);
*(matrix + j * cols + i) = temp;
}
}
}
void printMatrix(int *matrix, int rows, int cols) {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
printf("%d ", *(matrix + i * cols + j));
}
printf("\n");
}
}
int main() {
int matrix[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
printf("原始矩阵:\n");
printMatrix((int *)matrix, 3, 3);
transposeMatrix((int *)matrix, 3, 3);
printf("转置后的矩阵:\n");
printMatrix((int *)matrix, 3, 3);
return 0;
}
```
在这个示例中,我们使用一个二维数组 `matrix` 来表示矩阵。通过将它强制转换为 `int*` 类型的指针,我们可以对其进行指针操作。
`transposeMatrix` 函数使用两个嵌套的循环来遍历矩阵的上三角部分,并交换对应位置的元素值来实现转置。
`printMatrix` 函数用于打印矩阵的元素。
最后,在 `main` 函数中,我们创建一个 3x3 的矩阵,并依次打印原始矩阵和转置后的矩阵。
希望这个示例能够帮助你理解如何使用指针进行矩阵转置。如果有任何疑问,请随时提问。
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)