I have a problem with this code. I have to calculate a transposed matrix using dynamic allocation. The code works with 2x2 matrix but when I increase the matrix's size (like 3x3) it fails. Someone can help me?
#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;
}