Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- /*
- Working version that uses int ***ptr in function formal parameters for the 2d arrays.
- */
- void getRowCol(int *row, int *col){
- // Get Dimensions
- printf("Enter row-col: ");
- scanf("%d-%d", row, col);
- }
- void createMat(int ***mat, int row, int col){
- // Allocate memory for a matrix
- int i;
- *mat = (int **)malloc(sizeof(int *)*row);
- for(i=0; i<row; ++i){
- *(*mat+i) = (int *)malloc(sizeof(int *)*col);
- }
- }
- void inputVal(int ***mat, int row, int col){
- // Iterate through each cell and ask for input
- int i, j;
- for(i=0; i<row; ++i){
- for(j=0; j<col; ++j){
- printf("Enter value in A%d%d: ", i+1, j+1);
- scanf("%d", (*(*mat+i)+j));
- }
- }
- }
- void showMat(int ***mat, int row, int col){
- // Print the cells
- int i, j;
- for(i=0; i<row; ++i){
- for(j=0; j<col; ++j){
- printf(" %d ", *(*(*mat+i)+j));
- }
- printf("\n");
- }
- }
- void transposeMat(int ***mat, int ***transpose, int row, int col){
- /* Iterate through each cell in initial matrix
- and put the value in the transposed cell*/
- int i, j;
- for(i=0; i<row; ++i){
- for(j=0; j<col; ++j){
- *(*(*transpose+j)+i) = *(*(*mat+i)+j);
- }
- }
- }
- void freeMat(int ***mat, int row){
- // Free each allocated pointer to avoid memory leaks
- for(int i=0; i<row; ++i){
- free(*(*mat+i));
- }
- free(*mat);
- }
- int main(){
- int row, col, **matrix, **transpose;
- // Get Dimensions
- getRowCol(&row, &col);
- printf("Matrix is %d by %d\n", row, col);
- // Create Matrices
- createMat(&matrix, row, col);
- createMat(&transpose, col, row);
- // Get Values for the Initial Matrix
- inputVal(&matrix, row, col);
- // Show Initial Matrix
- printf("Initial Matrix\n");
- showMat(&matrix, row, col);
- // Transpose and Show
- printf("Transposed Matrix\n");
- transposeMat(&matrix, &transpose, row, col);
- showMat(&transpose, col, row);
- freeMat(&matrix, row);
- freeMat(&transpose, col);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement