用C语言编写一个程序,要求:编写一个矩阵转置函数,矩阵的行数和列数由输入数据给定。要求使用动态内存分 配实现。
时间: 2023-06-13 12:07:06 浏览: 67
以下是用C语言编写的矩阵转置函数程序,使用了动态内存分配:
```c
#include <stdio.h>
#include <stdlib.h>
void transpose(int **matrix, int rows, int cols) {
int i, j, temp;
// Transpose the matrix
for (i = 0; i < rows; i++) {
for (j = i+1; j < cols; j++) {
temp = matrix[i][j];
matrix[i][j] = matrix[j][i];
matrix[j][i] = temp;
}
}
}
int main() {
int i, j, rows, cols;
int **matrix;
printf("Enter the number of rows: ");
scanf("%d", &rows);
printf("Enter the number of columns: ");
scanf("%d", &cols);
// Allocate memory for the matrix
matrix = (int **)malloc(rows * sizeof(int *));
for (i = 0; i < rows; i++) {
matrix[i] = (int *)malloc(cols * sizeof(int));
}
// Read in the matrix
printf("Enter the matrix elements:\n");
for (i = 0; i < rows; i++) {
for (j = 0; j < cols; j++) {
scanf("%d", &matrix[i][j]);
}
}
// Transpose the matrix
transpose(matrix, rows, cols);
// Print the transposed matrix
printf("The transposed matrix is:\n");
for (i = 0; i < cols; i++) {
for (j = 0; j < rows; j++) {
printf("%d ", matrix[j][i]);
}
printf("\n");
}
// Free the memory
for (i = 0; i < rows; i++) {
free(matrix[i]);
}
free(matrix);
return 0;
}
```
该程序使用了一个名为 `transpose()` 的函数来执行矩阵转置操作。该函数接受一个二维整数指针、矩阵的行数和列数作为参数。在函数内部,使用两个循环来交换矩阵中对角线以下的元素和对角线以上的元素。最后,程序在 `main()` 函数中调用 `transpose()` 函数来转置输入的矩阵,并打印输出转置后的矩阵。程序还使用 `malloc()` 函数动态分配内存来创建矩阵。在程序结束时,使用 `free()` 函数释放分配的内存。