PPS Lab · Experiment 21
Transpose of a matrix with dynamic memory allocation
CArrays, pointers and functionsJNTUH R22 · CS108ES
Aim
To write a C program that reads an r × c matrix and finds its transpose, storing the transpose in a new c × r matrix whose memory is allocated at run time with malloc.
Algorithm
- Read the number of rows r and columns c (each between 1 and 10), then read the r × c elements of matrix A.
- Allocate an array of c row pointers with
malloc. For each of the c rows, allocate space for r integers. If anymallocreturns NULL, print an error and stop. - For every i from 0 to r − 1 and j from 0 to c − 1, set T[j][i] = A[i][j].
- Print the original matrix and the c × r transpose.
- Free each row of T, then free the array of row pointers.
Program
#include <stdio.h>
#include <stdlib.h>
#define MAX 10
/* Allocate a rows x cols matrix as an array of row pointers */
int **allocate_matrix(int rows, int cols) {
int **m = malloc(rows * sizeof(int *));
if (m == NULL) {
return NULL;
}
for (int i = 0; i < rows; i++) {
m[i] = malloc(cols * sizeof(int));
if (m[i] == NULL) {
for (int k = 0; k < i; k++) {
free(m[k]);
}
free(m);
return NULL;
}
}
return m;
}
void free_matrix(int **m, int rows) {
for (int i = 0; i < rows; i++) {
free(m[i]);
}
free(m);
}
int main(void) {
int a[MAX][MAX], rows, cols;
printf("Enter the number of rows and columns: ");
if (scanf("%d %d", &rows, &cols) != 2 || rows < 1 || rows > MAX || cols < 1 || cols > MAX) {
printf("Rows and columns must be between 1 and %d\n", MAX);
return 1;
}
printf("Enter the elements of the %d x %d matrix:\n", rows, cols);
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if (scanf("%d", &a[i][j]) != 1) {
printf("Invalid input\n");
return 1;
}
}
}
/* The transpose has cols rows and rows columns */
int **t = allocate_matrix(cols, rows);
if (t == NULL) {
printf("Memory allocation failed\n");
return 1;
}
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
t[j][i] = a[i][j];
}
}
printf("Original matrix (%d x %d):\n", rows, cols);
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
printf("%5d", a[i][j]);
}
printf("\n");
}
printf("Transpose (%d x %d):\n", cols, rows);
for (int i = 0; i < cols; i++) {
for (int j = 0; j < rows; j++) {
printf("%5d", t[i][j]);
}
printf("\n");
}
free_matrix(t, cols);
return 0;
}Output
A 2 x 4 matrix
Enter the number of rows and columns: 2 4
Enter the elements of the 2 x 4 matrix:
1 2 3 4
5 6 7 8
Original matrix (2 x 4):
1 2 3 4
5 6 7 8
Transpose (4 x 2):
1 5
2 6
3 7
4 8A 3 x 2 matrix
Enter the number of rows and columns: 3 2
Enter the elements of the 3 x 2 matrix:
10 20
30 40
50 60
Original matrix (3 x 2):
10 20
30 40
50 60
Transpose (2 x 3):
10 30 50
20 40 60Recorded by compiling and running this exact program. Typed input appears after each prompt.
How it works
The syllabus asks for dynamic memory only for the new matrix, so the input matrix is an ordinary 2-D array and only the transpose is allocated with malloc.
The transpose of an r × c matrix is a c × r matrix, so when r and c differ it cannot be stored in the same shape. Allocating it at run time lets it have exactly c rows of r integers.
t is a pointer to an array of row pointers, and each row pointer points to its own block of integers. That is why t[j][i] works like a normal 2-D array, and why each row must be freed before the array of pointers.
Common mistakes
Allocating the transpose with
rowsrow pointers ofcolsintegers, the same shape as the input. For a non-square matrix,t[j][i]then goes outside the allocated memory. The transpose needscolsrows ofrowsintegers.Not checking whether
mallocreturnedNULL. Using aNULLpointer crashes the program.Freeing only
tand not eacht[i]first. The row blocks are then never released (a memory leak). Free the rows, then the pointer array.Writing
malloc(rows * sizeof(int))for the array of row pointers. It must hold pointers, so usesizeof(int *), which can be a different size fromint.
Viva questions
Try to answer each one aloud before you open it.
What is the transpose of a matrix?
The matrix obtained by turning rows into columns: element (i, j) of A becomes element (j, i) of the transpose. An r × c matrix has a c × r transpose.
What does malloc return, and what if it fails?
It returns a pointer to a block of the requested number of bytes. If the memory cannot be allocated, it returns
NULL.What is the difference between malloc and calloc?
malloc(size)allocates one block and leaves its contents uninitialised.calloc(count, size)allocates space for count items of the given size and sets every byte to zero.What is a memory leak?
Memory allocated with
mallocthat is never released withfree. The program keeps holding it even though it no longer uses it.Which header file declares malloc and free?
stdlib.h.Why use dynamic allocation for the transpose here?
The size of the transpose depends on the rows and columns typed at run time and is different from the input's shape when the matrix is not square.
mallocgives exactly the memory needed for that size.