我的代码有问题。我必须使用动态分配来计算转置矩阵。代码使用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-Assign\n");
printMat(matrix, line, colum);
assignMat(matrix, line, colum);
printf("After-Assign\n");
printMat(matrix, line, colum);
copy_matrix = copyMat(matrix, line, colum);
printf("Matrix Copied\n");
printMat(copy_matrix, line, colum);
trasp_matrix = traspMat(matrix, line, colum);
printf("Transposed matrix\n");
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;
}
答案 0 :(得分:0)
请注意,malloc(line * sizeof(int))
分配了line
个整数,而不是line
个指针。如果sizeof(int) != sizeof(int*)
会给您带来很大的麻烦。
–一些程序员花花公子
改为使用int **m = malloc(line * sizeof(*m));
。
–RoadRunner