Skip to content
Laviyx Learn

Try

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

  1. Read the number of rows r and columns c (each between 1 and 10), then read the r × c elements of matrix A.
  2. Allocate an array of c row pointers with malloc. For each of the c rows, allocate space for r integers. If any malloc returns NULL, print an error and stop.
  3. For every i from 0 to r − 1 and j from 0 to c − 1, set T[j][i] = A[i][j].
  4. Print the original matrix and the c × r transpose.
  5. Free each row of T, then free the array of row pointers.

Program

C
#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

Output 1
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    8

A 3 x 2 matrix

Output 2
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   60

Recorded 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 rows row pointers of cols integers, the same shape as the input. For a non-square matrix, t[j][i] then goes outside the allocated memory. The transpose needs cols rows of rows integers.

  • Not checking whether malloc returned NULL. Using a NULL pointer crashes the program.

  • Freeing only t and not each t[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 use sizeof(int *), which can be a different size from int.

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 malloc that is never released with free. 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. malloc gives exactly the memory needed for that size.

Learn the concepts

All Programming for Problem Solving Lab experiments →