c语言 - 动态分配和矩阵



我对这段代码有问题。我必须使用动态分配计算转置矩阵。该代码适用于 2x2 矩阵,但是当我增加矩阵的大小(如 3x3)时,它会失败。有人可以帮助我吗?

#include <stdio.h>
#include <stdlib.h>
#define LINE 2
#define COLUMN 2

int** createMat(int line,int colum);
void printMat(int **m, int line,int colum);
void assignMat(int **m, int line, int colum);
int** copyMat(int **m, int line, int colum);
int** traspMat(int **m, int line, int colum);
int main(int argc, char **argv){
int line = LINE;
int colum = COLUMN;
int **matrix;
int **copy_matrix;
int **trasp_matrix;
matrix = createMat(line, colum);
printf("Pre-Assignn");
printMat(matrix, line, colum);
assignMat(matrix, line, colum);
printf("After-Assignn");
printMat(matrix, line, colum);
copy_matrix = copyMat(matrix, line, colum);
printf("Matrix Copiedn");
printMat(copy_matrix, line, colum);
trasp_matrix = traspMat(matrix, line, colum);
printf("Transposed matrixn");
printMat(trasp_matrix, line, colum);
free(matrix);
free(copy_matrix);
free(trasp_matrix);
return 0;
}
int** createMat(int line,int colum){
int **m = (int**)malloc(line * sizeof(int));
for(int i = 0; i < line; i++){
m[i] = (int*)malloc(colum * sizeof(int));
}
return m;
}
void printMat(int **m, int line,int colum){
for(int i = 0; i < line; i++){
for(int j = 0; j < colum; j++){
printf("%d  ", m[i][j]);
}
printf("n");
}
}
void assignMat(int **m, int line, int colum){
printf("Inserisci i valori nella matrice (per riga)n");
for (int i = 0; i < line; i++){
for(int j = 0; j < colum; j++){
printf("> ");
scanf(" %d", &m[i][j]);
}
}
printf("n");
}
int** copyMat(int **m, int line, int colum){
int **new_mat = createMat(line, colum);
for(int i = 0; i < line; i++){
for(int j = 0; j < colum; j++){
new_mat[i][j] = m[i][j];
}
}
return new_mat;
}
int** traspMat(int **m, int line, int colum){
int **new_m = createMat(line, colum);
for(int i = 0; i < line; i++){
for(int j = 0; j < colum; j++){
new_m[i][j] = m[j][i];
}
}
return new_m;
}

请注意,malloc(line * sizeof(int))分配line整数数,而不是line指针数。如果sizeof(int) != sizeof(int*)那么你就有大麻烦了。 - 一些程序员伙计

请改用int **m = malloc(line * sizeof(*m));。 – 路跑者

相关内容

  • 没有找到相关文章

最新更新