C Online Compiler
Example: Matrix Transpose Using Pointers in C
C
C++
C#
Java
Python
PHP
main.c
STDIN
Run
// Matrix Transpose Using Pointers #include <stdio.h> #define ROWS 2 #define COLS 3 void printMatrix(int *matrix, int rows, int cols) { for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { // Access element using pointer arithmetic: *(matrix + i * cols + j) printf("%d ", *(matrix + i * cols + j)); } printf("\n"); } } void transposeMatrix(int *original, int *transposed, int rows, int cols) { // Step 1: Iterate through rows of the original matrix for (int i = 0; i < rows; i++) { // Step 2: Iterate through columns of the original matrix for (int j = 0; j < cols; j++) { // Step 3: Calculate the memory address of the current element in the original matrix // For a 2D array treated as 1D, element (i, j) is at index (i * cols + j) int *original_element_ptr = original + (i * cols + j); // Step 4: Calculate the memory address for the transposed position in the new matrix // In the transposed matrix, original[i][j] becomes transposed[j][i]. // For the transposed matrix (cols x rows), element (j, i) is at index (j * rows + i) int *transposed_element_ptr = transposed + (j * rows + i); // Step 5: Assign the value from the original matrix to the transposed matrix *transposed_element_ptr = *original_element_ptr; } } } int main() { int originalMatrix[ROWS][COLS] = { {1, 2, 3}, {4, 5, 6} }; // The transposed matrix will have COLS rows and ROWS columns int transposedMatrix[COLS][ROWS]; printf("Original Matrix:\n"); // Pass the base address of the 2D array to the function printMatrix((int *)originalMatrix, ROWS, COLS); // Call the transpose function, passing base addresses and dimensions transposeMatrix((int *)originalMatrix, (int *)transposedMatrix, ROWS, COLS); printf("\nTransposed Matrix:\n"); // Print the transposed matrix (note dimensions are swapped for printMatrix) printMatrix((int *)transposedMatrix, COLS, ROWS); return 0; }
Output
Clear
ADVERTISEMENTS