C Online Compiler
Example: Transpose Static Matrix using Pointers in C
C
C++
C#
Java
Python
PHP
main.c
STDIN
Run
// Transpose Static Matrix using Pointers #include <stdio.h> // Function to print a matrix void printMatrix(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 * cols + j)); } printf("\n"); } } // Function to transpose a matrix using pointers void transposeMatrix(int *original, int *transposed, int rows, int cols) { // Iterate through the original matrix for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { // original[i][j] becomes transposed[j][i] // Access original[i][j] as *(original + i * cols + j) // Store it in transposed[j][i] as *(transposed + j * rows + i) *(transposed + j * rows + i) = *(original + i * cols + j); } } } int main() { // Step 1: Define original matrix dimensions int rows = 3; int cols = 2; // Step 2: Declare static original matrix and its transpose int originalMatrix[3][2] = { {1, 2}, {3, 4}, {5, 6} }; int transposedMatrix[2][3]; // Transposed matrix will have cols x rows dimensions printf("Original Matrix (%dx%d):\n", rows, cols); // Pass originalMatrix as (int*) to print function printMatrix((int*)originalMatrix, rows, cols); // Step 3: Transpose the matrix using the function // Pass originalMatrix and transposedMatrix as (int*) transposeMatrix((int*)originalMatrix, (int*)transposedMatrix, rows, cols); printf("\nTransposed Matrix (%dx%d):\n", cols, rows); // Pass transposedMatrix as (int*) to print function (note new rows/cols for printing) printMatrix((int*)transposedMatrix, cols, rows); return 0; }
Output
Clear
ADVERTISEMENTS