Chatgpt校正版:
#include <stdlib.h>
#include <stdio.h>
double** allocateMatrix(int rows, int cols) {
double **matrix = (double**) calloc(rows, sizeof(double*));
if (!matrix) {
printf("Memory allocation failed.\n");
return NULL;
}
for (int i = 0; i < rows; i++) {
matrix[i] = (double*) calloc(cols, sizeof(double));
if (!matrix[i]) {
printf("Memory allocation failed.\n");
while (i-- > 0) {
free(matrix[i]);
}
free(matrix);
return NULL;
}
}
return matrix;
}
void freeMatrix(double** matrix, int rows) {
for (int i = 0; i < rows; i++) {
free(matrix[i]);
}
free(matrix);
}
double** transposeMatrix(double **matrix, int rows, int cols) {
double **transposed = allocateMatrix(cols, rows);
if (!transposed) return NULL;
for (int i = 0; i < cols; i++) {
for (int j = 0; j < rows; j++) {
transposed[i][j] = matrix[j][i];
}
}
return transposed;
}
void printMatrix(double **matrix, int rows, int cols) {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
printf("%5.3g ", matrix[i][j]);
if ((cols != 1) && (j + 1) % cols == 0) {
printf("\n");
}
}
}
printf("\n");
}
void initializeMatrix(double **matrix, int rows, int cols) {
for (int i = 0; i < rows; i++) {
for (int j = 0, value = i; j < cols; j++, value += j * j) {
matrix[i][j] = value;
}
}
}
int main() {
int rows = 2, cols = 5;
double **matrix, **transposed;
matrix = allocateMatrix(rows, cols);
if (!matrix) return 0;
initializeMatrix(matrix, rows, cols);
transposed = transposeMatrix(matrix, rows, cols);
if (!transposed) {
freeMatrix(matrix, rows);
return 0;
}
printMatrix(matrix, rows, cols);
printMatrix(transposed, cols, rows);
freeMatrix(matrix, rows);
freeMatrix(transposed, cols);
return 0;
}
【 在 sqsl 的大作中提到: 】
: 我写了一段计算矩阵的转置矩阵的程序,运行虽然没有报错,但是我觉得我程序里是不是有两个错误?
: (1)验证了if( AT == NULL )之后,没必要再验证if( AT[i] == NULL )吧?属于多此一举;
: (2)定义**XT后缺少生成2行5列的全零矩阵的步骤。程序这次虽然没有出错,但容易出现内存地址被占用的情况?
: ...................
--
FROM 192.102.204.*