Advertisement
aaaranes

Transpose of a matrix in C

Mar 21st, 2024
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.10 KB | Source Code | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. /*
  4.     Working version that uses int ***ptr in function formal parameters for the 2d arrays.
  5. */
  6.  
  7. void getRowCol(int *row, int *col){
  8.     // Get Dimensions
  9.     printf("Enter row-col: ");
  10.     scanf("%d-%d", row, col);
  11. }
  12.  
  13. void createMat(int ***mat, int row, int col){
  14.     // Allocate memory for a matrix
  15.     int i;
  16.     *mat = (int **)malloc(sizeof(int *)*row);
  17.    
  18.     for(i=0; i<row; ++i){
  19.         *(*mat+i) = (int *)malloc(sizeof(int *)*col);
  20.     }
  21. }
  22.  
  23. void inputVal(int ***mat, int row, int col){
  24.     // Iterate through each cell and ask for input
  25.     int i, j;
  26.     for(i=0; i<row; ++i){
  27.         for(j=0; j<col; ++j){
  28.             printf("Enter value in A%d%d: ", i+1, j+1);
  29.             scanf("%d", (*(*mat+i)+j));
  30.         }
  31.     }
  32. }
  33.  
  34. void showMat(int ***mat, int row, int col){
  35.     // Print the cells
  36.     int i, j;
  37.     for(i=0; i<row; ++i){
  38.         for(j=0; j<col; ++j){
  39.             printf(" %d ", *(*(*mat+i)+j));
  40.         }
  41.         printf("\n");
  42.     }
  43. }
  44.  
  45. void transposeMat(int ***mat, int ***transpose, int row, int col){
  46.     /* Iterate through each cell in initial matrix
  47.     and put the value in the transposed cell*/
  48.     int i, j;
  49.     for(i=0; i<row; ++i){
  50.         for(j=0; j<col; ++j){
  51.             *(*(*transpose+j)+i) = *(*(*mat+i)+j);
  52.         }
  53.     }
  54. }
  55.  
  56. void freeMat(int ***mat, int row){
  57.     // Free each allocated pointer to avoid memory leaks
  58.     for(int i=0; i<row; ++i){
  59.         free(*(*mat+i));
  60.     }
  61.     free(*mat);
  62. }
  63.  
  64. int main(){
  65.     int row, col, **matrix, **transpose;
  66.     // Get Dimensions
  67.     getRowCol(&row, &col);
  68.     printf("Matrix is %d by %d\n", row, col);
  69.    
  70.     // Create Matrices
  71.     createMat(&matrix, row, col);
  72.     createMat(&transpose, col, row);
  73.    
  74.     // Get Values for the Initial Matrix
  75.     inputVal(&matrix, row, col);
  76.    
  77.     // Show Initial Matrix
  78.     printf("Initial Matrix\n");
  79.     showMat(&matrix, row, col);
  80.    
  81.     // Transpose and Show
  82.     printf("Transposed Matrix\n");
  83.     transposeMat(&matrix, &transpose, row, col);
  84.     showMat(&transpose, col, row);
  85.    
  86.     freeMat(&matrix, row);
  87.     freeMat(&transpose, col);
  88.     return 0;  
  89. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement