C Online Compiler
Example: Transpose Dynamic Matrix using Pointers in C
C
C++
C#
Java
Python
PHP
main.c
STDIN
Run
// Transpose Dynamic Matrix using Pointers #include <stdio.h> #include <stdlib.h> // Required for malloc and free // Function to allocate memory for a dynamic matrix int** allocateMatrix(int rows, int cols) { int** matrix = (int**)malloc(rows * sizeof(int*)); if (matrix == NULL) { perror("Failed to allocate memory for rows"); exit(EXIT_FAILURE); } for (int i = 0; i < rows; i++) { matrix[i] = (int*)malloc(cols * sizeof(int)); if (matrix[i] == NULL) { perror("Failed to allocate memory for columns"); // Free previously allocated rows for (int k = 0; k < i; k++) { free(matrix[k]); } free(matrix); exit(EXIT_FAILURE); } } return matrix; } // Function to free memory of a dynamic matrix void freeMatrix(int** matrix, int rows) { for (int i = 0; i < rows; i++) { free(matrix[i]); } free(matrix); } // Function to print a dynamic matrix void printDynamicMatrix(int** matrix, int rows, int cols) { for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { printf("%d\t", matrix[i][j]); } printf("\n"); } } // Function to transpose a dynamic matrix void transposeDynamicMatrix(int** original, int** transposed, int rows, int cols) { for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { // original[i][j] becomes transposed[j][i] transposed[j][i] = original[i][j]; } } } int main() { // Step 1: Define original matrix dimensions int rows = 2; int cols = 3; // Step 2: Allocate memory for original and transposed matrices int** originalMatrix = allocateMatrix(rows, cols); int** transposedMatrix = allocateMatrix(cols, rows); // Transposed will be cols x rows // Step 3: Initialize original matrix (example data) int count = 1; for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { originalMatrix[i][j] = count++; } } printf("Original Matrix (%dx%d):\n", rows, cols); printDynamicMatrix(originalMatrix, rows, cols); // Step 4: Transpose the matrix transposeDynamicMatrix(originalMatrix, transposedMatrix, rows, cols); printf("\nTransposed Matrix (%dx%d):\n", cols, rows); printDynamicMatrix(transposedMatrix, cols, rows); // Step 5: Free allocated memory freeMatrix(originalMatrix, rows); freeMatrix(transposedMatrix, cols); return 0; }
Output
Clear
ADVERTISEMENTS